The subprocess.Popen() module

The Popen class handles the process creation and management. By using this module, developers can handle less common cases. The child program execution will be done in a new process. To execute a child program on Unix/Linux, the class will use the os.execvp() function. To execute a child program in Windows, the class will use the CreateProcess() function.

Now, let's see some useful arguments of subprocess.Popen():

class subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None,
stderr=None, preexec_fn=None, close_fds=False, shell=False,
cwd=None, env=None, universal_newlines=False,
startupinfo=None, creationflags=0)

Let's look at each argument:

  • args: It can be a sequence of program arguments or a single string. If args is a sequence, the first item in args is executed. If args is a string, it recommends to pass args as a sequence.
  • shell: The shell argument is by default set to False and it specifies whether to use shell for execution of the program. If shell is True, it recommends to pass args as a string. In Linux, if shell=True, the shell defaults to /bin/sh. If args is a string, the string specifies the command to execute through the shell.
  • bufsize: If bufsize is 0 (by default, it is 0), it means unbuffered and if bufsize is 1, it means line buffered. If bufsize is any other positive value, use a buffer of the given size. If bufsize is any other negative value, it means fully buffered.
  • executable: It specifies that the replacement program to be executed. 
  • stdin, stdout, and stderr: These arguments define the standard input, standard output, and standard error respectively. 
  • preexec_fn: This is set to a callable object and will be called just before the child is executed in the child process.
  • close_fds: In Linux, if close_fds is true, all file descriptors except 0, 1, and 2 will be closed before the child process is executed. In Windows, if close_fds is true then the child process will inherit no handles. 
  • env: If the value is not None, then mapping will define environment variables for new process.
  • universal_newlines: If the value is True then stdout and stderr will be opened as text files in newlines mode.

Now, we are going to see an example of subprocess.Popen(). For that, create a ssh_using_sub.py  script and write the following content in it:

import subprocess
import sys

HOST="your host username@host ip"
COMMAND= "ls"

ssh_obj = subprocess.Popen(["ssh", "%s" % HOST, COMMAND],
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)

result = ssh_obj.stdout.readlines()
if result == []:
err = ssh_obj.stderr.readlines()
print(sys.stderr, "ERROR: %s" % err)
else:
print(result)

Run the script and you will get the output as follows:

student@ubuntu:~$ python3 ssh_using_sub.py
Output :
[email protected]'s password:
[b'Desktop ', b'Documents ', b'Downloads ', b'examples.desktop ', b'Music ', b'Pictures ', b'Public ', b'sample.py ', b'spark ', b'spark-2.3.1-bin-hadoop2.7 ', b'spark-2.3.1-bin-hadoop2.7.tgz ', b'ssh ', b'Templates ', b'test_folder ', b'test.txt ', b'Untitled1.ipynb ', b'Untitled.ipynb ', b'Videos ', b'work ']

In the preceding example, first, we imported the subprocess module, then we defined the host address where you want to establish the SSH connection. After that, we gave one simple command that executed over the remote device. After all this was set up, we put this information in the subprocess.Popen() function. This function executed the arguments defined inside that function to create a connection with the remote device. After the SSH connection was established, our defined command was executed and provided the result. Then we printed the result of SSH on the Terminal, as shown in the output.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset