我想创建一个将返回 shell 输出的函数,我有这样的东西:
def shell_exec(code):
buff = StringIO.StringIO()
subprocess.call(code, shell=True, stdout=buff)
return buff.getvalue()
但出现错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in shell_exec
File "/usr/lib/python2.7/subprocess.py", line 524, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 703, in __init__
errread, errwrite) = self._get_handles(stdin, stdout, stderr)
File "/usr/lib/python2.7/subprocess.py", line 1115, in _get_handles
c2pwrite = stdout.fileno()
AttributeError: StringIO instance has no attribute 'fileno'
使用 subprocess.check_output
.它返回命令输出。
def shell_exec(code):
try:
return subprocess.check_output(code, shell=True)
except subprocess.CalledProcessError as e:
return e.output
顺便说一句,stdin
、stdout
、stderr
的有效值是PIPE
、DEVNULL
、现有文件描述符(正整数)、现有文件对象和None
。