不幸的是,你已经标记了这个python-2.7,就像在 python 3.5 及更高版本中一样,使用run() 会很简单:
import subprocess
output = subprocess.run(..., stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE).stderr
使用check_output() stdout 根本无法重定向:
>>> subprocess.check_output(('ls', 'asdfqwer'), stdout=open(os.devnull, 'wb'), stderr=subprocess.STDOUT)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/subprocess.py", line 566, in check_output
raise ValueError('stdout argument not allowed, it will be overridden.')
ValueError: stdout argument not allowed, it will be overridden.
将Popen 对象和communicate() 与低于3.5 的python 版本一起使用。在 python 2.7 中使用os.devnull 打开/dev/null:
>>> import subprocess
>>> import os
>>> with open(os.devnull, 'wb') as devnull:
... proc = subprocess.Popen(('ls', 'asdfqwer'),
... stdout=devnull,
... stderr=subprocess.PIPE)
... proc.communicate()
... proc.returncode
...
(None, "ls: cannot access 'asdfqwer': No such file or directory\n")
2
通信将输入发送到标准输入(如果通过管道传输),并从标准输出和标准错误读取,直到到达文件结尾。