Python2與Python3的區別(八):commands與subprocess
36.16. commands — Utilities for running commands
Deprecated since version 2.6: The commands module has been removed in Python 3. Use the subprocess module instead.
The commands module contains wrapper functions for os.popen() which take a system command as a string and return any output generated by the command and, optionally, the exit status.
The subprocess module provides more powerful facilities for spawning new processes and retrieving their results. Using the subprocess module is preferable to using the commands module.
Note
In Python 3.x, getstatus() and two undocumented functions (mk2arg() and mkarg()) have been removed. Also, getstatusoutput() and getoutput() have been moved to the subprocess module.
The commands module defines the following functions:
commands.getstatusoutput(cmd)
Execute the string cmd in a shell with os.popen() and return a 2-tuple (status, output). cmd is actually run as { cmd ; } 2>&1, so that the returned output will contain output or error messages. A trailing newline is stripped from the output. The exit status for the command can be interpreted according to the rules for the C function wait().
commands.getoutput(cmd)
Like getstatusoutput(), except the exit status is ignored and the return value is a string containing the command’s output.
commands.getstatus(file)
Return the output of ls -ld file as a string. This function uses the getoutput() function, and properly escapes backslashes and dollar signs in the argument.
Deprecated since version 2.6: This function is nonobvious and useless. The name is also misleading in the presence of getstatusoutput().
Example:
>>> import commands
>>> commands.getstatusoutput('ls /bin/ls')
(0, ‘/bin/ls’)
>>> commands.getstatusoutput('cat /bin/junk')
(256, 'cat: /bin/junk: No such file or directory')
>>> commands.getstatusoutput('/bin/junk')
(256, 'sh: /bin/junk: not found')
>>> commands.getoutput('ls /bin/ls')
'/bin/ls'
>>> commands.getstatus('/bin/ls')
'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'
**********************************************
17.5.1. Using the subprocess Module
The recommended approach to invoking subprocesses is to use the run() function for all use cases it can handle. For more advanced use cases, the underlying Popen interface can be used directly.
The run() function was added in Python 3.5; if you need to retain compatibility with older versions, see the Older high-level API section.
subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False)
Run the command described by args. Wait for command to complete, then return a CompletedProcess instance.
The arguments shown above are merely the most common ones, described below in Frequently Used Arguments (hence the use of keyword-only notation in the abbreviated signature). The full function signature is largely the same as that of the Popen constructor - apart from timeout, input and check, all the arguments to this function are passed through to that interface.
This does not capture stdout or stderr by default. To do so, pass PIPE for the stdout and/or stderr arguments.
The timeout argument is passed to Popen.communicate(). If the timeout expires, the child process will be killed and waited for. The TimeoutExpired exception will be re-raised after the child process has terminated.
The input argument is passed to Popen.communicate() and thus to the subprocess’s stdin. If used it must be a byte sequence, or a string if universal_newlines=True. When used, the internal Popen object is automatically created with stdin=PIPE, and the stdin argument may not be used as well.
If check is True, and the process exits with a non-zero exit code, a CalledProcessError exception will be raised. Attributes of that exception hold the arguments, the exit code, and stdout and stderr if they were captured.
Examples:
>>> subprocess.run(["ls", "-l"]) # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)
>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
>>> subprocess.run(["ls", "-l", "/dev/null"], stdout=subprocess.PIPE)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n')
New in version 3.5.
class subprocess.CompletedProcess
The return value from run(), representing a process that has finished.
args
The arguments used to launch the process. This may be a list or a string.
returncode
Exit status of the child process. Typically, an exit status of 0 indicates that it ran successfully.
A negative value -N indicates that the child was terminated by signal N (POSIX only).
stdout
Captured stdout from the child process. A bytes sequence, or a string if run() was called with universal_newlines=True. None if stdout was not captured.
If you ran the process with stderr=subprocess.STDOUT, stdout and stderr will be combined in this attribute, and stderr will be None.
stderr
Captured stderr from the child process. A bytes sequence, or a string if run() was called with universal_newlines=True. None if stderr was not captured.
check_returncode()
If returncode is non-zero, raise a CalledProcessError.
New in version 3.5.
subprocess.DEVNULL
Special value that can be used as the stdin, stdout or stderr argument to Popen and indicates that the special file os.devnull will be used.
New in version 3.3.
subprocess.PIPE
Special value that can be used as the stdin, stdout or stderr argument to Popen and indicates that a pipe to the standard stream should be opened. Most useful with Popen.communicate().
subprocess.STDOUT
Special value that can be used as the stderr argument to Popen and indicates that standard error should go into the same handle as standard output.
exception subprocess.SubprocessError
Base class for all other exceptions from this module.
New in version 3.3.
exception subprocess.TimeoutExpired
Subclass of SubprocessError, raised when a timeout expires while waiting for a child process.
cmd
Command that was used to spawn the child process.
timeout
Timeout in seconds.
output
Output of the child process if it was captured by run() or check_output(). Otherwise, None.
stdout
Alias for output, for symmetry with stderr.
stderr
Stderr output of the child process if it was captured by run(). Otherwise, None.
New in version 3.3.
Changed in version 3.5: stdout and stderr attributes added
exception subprocess.CalledProcessError
Subclass of SubprocessError, raised when a process run by check_call() or check_output() returns a non-zero exit status.
returncode
Exit status of the child process. If the process exited due to a signal, this will be the negative signal number.
cmd
Command that was used to spawn the child process.
output
Output of the child process if it was captured by run() or check_output(). Otherwise, None.
stdout
Alias for output, for symmetry with stderr.
stderr
Stderr output of the child process if it was captured by run(). Otherwise, None.
Changed in version 3.5: stdout and stderr attributes added