Python2与Python3的区别(八):commands与subprocess

翻译 2016年08月29日 15:54:20

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

python commands模块在python3.x被subprocess取代

subprocess 可以执行shell命令的相关模块和函数有: os.system os.spawn os.popen --废弃 popen2.* --废弃 commands.* --废弃,3.x中...
  • RonnyJiang
  • RonnyJiang
  • 2016年11月25日 14:12
  • 6491

python-commands模块的适用

commands模块是python的内置模块,他共有三个函数,使用help(commands)可以查看到FUNCTIONS getoutput(cmd) Return outp...
  • guoqianqian5812
  • guoqianqian5812
  • 2016年08月04日 14:02
  • 3501

[Python] 利用commands模块执行Linux shell命令

用Python写运维脚本时,经常需要执行linux shell的命令,Python中的commands模块专门用于调用Linux shell命令,并返回状态和结果,下面是commands模块的3个主要...
  • u010415792
  • u010415792
  • 2013年07月22日 22:18
  • 24798

python模块commands

如何获取Shell命令的输出和返回值         可以使用commands模块        其中有三个函数   1、 commands。getstatusoutput(cmd)返回一个元组...
  • hym2111
  • hym2111
  • 2012年08月06日 10:20
  • 5428

python3 subprocess模块使用

subprocess 模块@(python3)官网说明文档subprocess.call 和 subprocess.check_call 执行命令,返回状态码。 两者唯一的区别在于返回...
  • CityzenOldwang
  • CityzenOldwang
  • 2017年10月29日 09:49
  • 417

Python_cmd的各种实现方法及优劣(subprocess.Popen, os.system和commands.getstatusoutput)

目前我使用到的python中执行cmd的方式有三种: 1. 使用os.system("cmd") 这是最简单的一种方法,特点是执行的时候程序会打出cmd在linux上执行的信息。使用前需要...
  • menglei8625
  • menglei8625
  • 2012年04月24日 16:15
  • 68539

python第三方库系列之十--commands库

我们这次讲的是利用commands模块执行Linux shell命令,当我们用Python写运维脚本时,经常需要执行linux shell的命令,Python中的commands模块专门用于调用Lin...
  • wenph2008
  • wenph2008
  • 2014年11月29日 00:09
  • 2325

Python2与Python3的区别(八):commands与subprocess

36.16. commands — Utilities for running commandsDeprecated since version 2.6: The commands module ha...
  • foryouslgme
  • foryouslgme
  • 2016年08月29日 15:54
  • 818

urllib库在python2与python3中的区别

python2与python3中会有一些语法的不同。python3是python2的升级版,在python2中,有urllib库与urllib2库,但是在python3中,都合并到urllib库中。此...
  • moll_77
  • moll_77
  • 2017年11月20日 14:16
  • 220

Python 3读写文件和Python2的区别

最近再看python处理csv的内容,查阅之前有python2 打开csv文件的操作: writer = csv.writer (open('test.csv','wb') 但是在pyth...
  • yujianmse
  • yujianmse
  • 2015年11月10日 14:24
  • 1015
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Python2与Python3的区别(八):commands与subprocess
举报原因:
原因补充:

(最多只允许输入30个字)