Using the Module The recommended way to launch subprocesses is to use the following convenience functions. For more advanced use cases when these do not meet your needs, use the underlying interface. Call ( args,., stdin=None, stdout=None, stderr=None, shell=False ) Run the command described by args. Wait for command to complete, then return the returncode attribute.
The arguments shown above are merely the most common ones, described below in (hence the slightly odd notation in the abbreviated signature). The full function signature is the same as that of the constructor - this functions passes all supplied arguments directly through to that interface. Note Do not use stdout=PIPE or stderr=PIPE with this function as that can deadlock based on the child process output volume. Use with the communicate method when you need pipes. Checkcall ( args,., stdin=None, stdout=None, stderr=None, shell=False ) Run command with arguments. Wait for command to complete.
If the return code was zero then return, otherwise raise. The object will have the return code in the attribute. The arguments shown above are merely the most common ones, described below in (hence the slightly odd notation in the abbreviated signature). The full function signature is the same as that of the constructor - this functions passes all supplied arguments directly through to that interface. Note Do not use stdout=PIPE or stderr=PIPE with this function as that can deadlock based on the child process output volume. Use with the communicate method when you need pipes.
Checkoutput ( args,., stdin=None, stderr=None, shell=False, universalnewlines=False ) Run command with arguments and return its output as a byte string. If the return code was non-zero it raises a. The object will have the return code in the attribute and any output in the attribute. The arguments shown above are merely the most common ones, described below in (hence the slightly odd notation in the abbreviated signature). The full function signature is largely the same as that of the constructor, except that stdout is not permitted as it is used internally.
Apr 02, 2019 Python » en 3.7.3. Here’s an example of how asyncio can run a shell command and obtain its result: import asyncio async def run (cmd). Because all asyncio subprocess functions are asynchronous and asyncio provides many tools to work with such functions, it is easy to execute and monitor multiple subprocesses in parallel. Using the subprocess Module¶ The recommended way to launch subprocesses is to use the following convenience functions. For more advanced use cases when these do not meet your needs, use the underlying Popen interface. Subprocess.call (args, *, stdin=None, stdout=None, stderr=None, shell=False) ¶ Run the command described by args.
All other supplied arguments are passed directly through to the constructor. Note Do not use stderr=PIPE with this function as that can deadlock based on the child process error volume. Use with the communicate method when you need a stderr pipe. PIPE Special value that can be used as the stdin, stdout or stderr argument to and indicates that a pipe to the standard stream should be opened. STDOUT Special value that can be used as the stderr argument to and indicates that standard error should go into the same handle as standard output. Exception subprocess.
CalledProcessError Exception raised when a process run by or returns a non-zero exit status. Returncode Exit status of the child process. Cmd Command that was used to spawn the child process.
Output Output of the child process if this exception is raised. Otherwise, None. Args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. To permit spaces in file names).
If passing a single string, either shell must be (see below) or else the string must simply name the program to be executed without specifying any arguments. Stdin, stdout and stderr specify the executed program’s standard input, standard output and standard error file handles, respectively. Valid values are, an existing file descriptor (a positive integer), an existing file object, and None. Indicates that a new pipe to the child should be created. With the default settings of None, no redirection will occur; the child’s file handles will be inherited from the parent. Additionally, stderr can be, which indicates that the stderr data from the child process should be captured into the same file handle as for stdout. When stdout or stderr are pipes and universalnewlines is True then all line endings will be converted to ' n' as described for the 'U' mode argument to.
If shell is True, the specified command will be executed through the shell. This can be useful if you are using Python primarily for the enhanced control flow it offers over most system shells and still want convenient access to other shell features such as shell pipes, filename wildcards, environment variable expansion, and expansion of to a user’s home directory. However, note that Python itself offers implementations of many shell-like features (in particular, and ). from subprocess import call filename = input ( 'What file would you like to display? N ' ) What file would you like to display? Nonexistent; rm -rf / # call ( 'cat ' + filename, shell = True ) # Uh-oh.
This will end badly. Shell=False disables all shell based features, but does not suffer from this vulnerability; see the Note in the constructor documentation for helpful hints in getting shell=False to work. When using shell=True, can be used to properly escape whitespace and shell metacharacters in strings that are going to be used to construct shell commands. These options, along with all of the other options, are described in more detail in the constructor documentation. Popen Constructor The underlying process creation and management in this module is handled by the class. It offers a lot of flexibility so that developers are able to handle the less common cases not covered by the convenience functions.
Class subprocess. Popen ( args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexecfn=None, closefds=False, shell=False, cwd=None, env=None, universalnewlines=False, startupinfo=None, creationflags=0 ) Execute a child program in a new process. On Unix, the class uses -like behavior to execute the child program.
On Windows, the class uses the Windows CreateProcess function. The arguments to are as follows. Args should be a sequence of program arguments or else a single string. By default, the program to execute is the first item in args if args is a sequence.
If args is a string, the interpretation is platform-dependent and described below. See the shell and executable arguments for additional differences from the default behavior. Unless otherwise stated, it is recommended to pass args as a sequence.
On Unix, if args is a string, the string is interpreted as the name or path of the program to execute. However, this can only be done if not passing arguments to the program. import shlex, subprocess commandline = rawinput /bin/vikings -input eggs.txt -output 'spam spam.txt' -cmd 'echo '$MONEY' args = shlex.
Split ( commandline ) print args '/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', 'echo '$MONEY' p = subprocess. Popen ( args ) # Success! Note in particular that options (such as -input) and arguments (such as eggs.txt) that are separated by whitespace in the shell go in separate list elements, while arguments that need quoting or backslash escaping when used in the shell (such as filenames containing spaces or the echo command shown above) are single list elements. On Windows, if args is a sequence, it will be converted to a string in a manner described in. This is because the underlying CreateProcess operates on strings.
The shell argument (which defaults to False) specifies whether to use the shell as the program to execute. If shell is True, it is recommended to pass args as a string rather than as a sequence.
On Unix with shell=True, the shell defaults to /bin/sh. If args is a string, the string specifies the command to execute through the shell. This means that the string must be formatted exactly as it would be when typed at the shell prompt. This includes, for example, quoting or backslash escaping filenames with spaces in them. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself.
That is to say, does the equivalent of. Note If you experience performance issues, it is recommended that you try to enable buffering by setting bufsize to either -1 or a large enough positive value (such as 4096). The executable argument specifies a replacement program to execute. It is very seldom needed. When shell=False, executable replaces the program to execute specified by args. However, the original args is still passed to the program.
Most programs treat the program specified by args as the command name, which can then be different from the program actually executed. On Unix, the args name becomes the display name for the executable in utilities such as ps. If shell=True, on Unix the executable argument specifies a replacement shell for the default /bin/sh. Stdin, stdout and stderr specify the executed program’s standard input, standard output and standard error file handles, respectively.
Valid values are, an existing file descriptor (a positive integer), an existing file object, and None. Indicates that a new pipe to the child should be created. With the default settings of None, no redirection will occur; the child’s file handles will be inherited from the parent.
Additionally, stderr can be, which indicates that the stderr data from the child process should be captured into the same file handle as for stdout. If preexecfn is set to a callable object, this object will be called in the child process just before the child is executed.
(Unix only) If closefds is true, all file descriptors except 0, 1 and 2 will be closed before the child process is executed. Or, on Windows, if closefds is true then no handles will be inherited by the child process. Note that on Windows, you cannot set closefds to true and also redirect the standard handles by setting stdin, stdout or stderr. If cwd is not None, the child’s current directory will be changed to cwd before it is executed. Note that this directory is not considered when searching the executable, so you can’t specify the program’s path relative to cwd. If env is not None, it must be a mapping that defines the environment variables for the new process; these are used instead of inheriting the current process’ environment, which is the default behavior.
Exceptions Exceptions raised in the child process, before the new program has started to execute, will be re-raised in the parent. Additionally, the exception object will have one extra attribute called childtraceback, which is a string containing traceback information from the child’s point of view. The most common exception raised is. This occurs, for example, when trying to execute a non-existent file. Applications should prepare for exceptions. A will be raised if is called with invalid arguments.
And will raise if the called process returns a non-zero return code. Warning This will deadlock when using stdout=PIPE and/or stderr=PIPE and the child process generates enough output to a pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use to avoid that. Communicate ( input=None ) Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child.
Returns a tuple (stdoutdata, stderrdata). Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too. Warning Use rather than, or to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process. Stdin If the stdin argument was, this attribute is a file object that provides input to the child process.
Otherwise, it is None. Stdout If the stdout argument was, this attribute is a file object that provides output from the child process. Otherwise, it is None. Stderr If the stderr argument was, this attribute is a file object that provides error output from the child process. Otherwise, it is None. Pid The process ID of the child process.
Note that if you set the shell argument to True, this is the process ID of the spawned shell. Returncode The child return code, set by and (and indirectly by ).
A None value indicates that the process hasn’t terminated yet. A negative value -N indicates that the child was terminated by signal N (Unix only). Si = subprocess. STARTUPINFO si.
DwFlags = subprocess. STARTFUSESTDHANDLES subprocess. STARTFUSESHOWWINDOW hStdInput If specifies, this attribute is the standard input handle for the process. If is not specified, the default for standard input is the keyboard buffer. HStdOutput If specifies, this attribute is the standard output handle for the process.
Otherwise, this attribute is ignored and the default for standard output is the console window’s buffer. HStdError If specifies, this attribute is the standard error handle for the process.
Otherwise, this attribute is ignored and the default for standard error is the console window’s buffer. WShowWindow If specifies, this attribute can be any of the values that can be specified in the nCmdShow parameter for the function, except for SWSHOWDEFAULT. Otherwise, this attribute is ignored. Is provided for this attribute.
It is used when is called with shell=True. Constants The module exposes the following constants. STDINPUTHANDLE The standard input device. Initially, this is the console input buffer, CONIN$. STDOUTPUTHANDLE The standard output device.
Initially, this is the active console screen buffer, CONOUT$. STDERRORHANDLE The standard error device. Initially, this is the active console screen buffer, CONOUT$. SWHIDE Hides the window. Another window will be activated. STARTFUSESTDHANDLES Specifies that the, and attributes contain additional information.
STARTFUSESHOWWINDOW Specifies that the attribute contains additional information. CREATENEWCONSOLE The new process has a new console, instead of inheriting its parent’s console (the default). This flag is always set when is created with shell=True.
CREATENEWPROCESSGROUP A creationflags parameter to specify that a new process group will be created. This flag is necessary for using on the subprocess. This flag is ignored if is specified. ( childstdin, childstdoutandstderr ) = os.
Popen4 ( 'cmd', mode, bufsize ) p = Popen ( 'cmd', shell = True, bufsize = bufsize, stdin = PIPE, stdout = PIPE, stderr = STDOUT, closefds = True ) ( childstdin, childstdoutandstderr ) = ( p. Stdout ) On Unix, os.popen2, os.popen3 and os.popen4 also accept a sequence as the command to execute, in which case arguments will be passed directly to the program without shell intervention. This usage can be replaced as follows. ( childstdout, childstdin ) = popen2.
Popen2 ( 'mycmd', 'myarg' , bufsize, mode ) p = Popen ( 'mycmd', 'myarg' , bufsize = bufsize, stdin = PIPE, stdout = PIPE, closefds = True ) ( childstdout, childstdin ) = ( p. Stdin ) and basically work as, except that:. raises an exception if the execution fails. the capturestderr argument is replaced with the stderr argument. stdin=PIPE and stdout=PIPE must be specified.
popen2 closes all file descriptors by default, but you have to specify closefds=True with. Converting an argument sequence to a string on Windows On Windows, an args sequence is converted to a string that can be parsed using the following rules (which correspond to the rules used by the MS C runtime):. Arguments are delimited by white space, which is either a space or a tab. A string surrounded by double quotation marks is interpreted as a single argument, regardless of white space contained within.
A quoted string can be embedded in an argument. A double quotation mark preceded by a backslash is interpreted as a literal double quotation mark.
Backslashes are interpreted literally, unless they immediately precede a double quotation mark. If backslashes immediately precede a double quotation mark, every pair of backslashes is interpreted as a literal backslash. If the number of backslashes is odd, the last backslash escapes the next double quotation mark as described in rule 3.