如何使用subprocess.call拦截来自Python shell exec的stdout?

时间:2014-03-01 10:30:45

标签: python shell python-2.7 exec subprocess

我想创建一个返回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'

1 个答案:

答案 0 :(得分:2)

使用subprocess.check_output。它返回命令输出。

def shell_exec(code):
    try:
        return subprocess.check_output(code, shell=True)
    except subprocess.CalledProcessError as e:
        return e.output

BTW,stdinstdoutstderr的有效值为PIPEDEVNULL,现有文件描述符(正整数),现有值文件对象和None