使用subprocess.call在内存中收集stderr

时间:2013-06-27 20:01:00

标签: python subprocess

我正在尝试在内存中收集stderr,而不是直接将其写入文件或标准输出。我这样做,所以我可以以某种方式生成错误日志文件。我发现了一个名为StringIO的库,它是一个内存中的'文件'。我不认为这样做。这是我的代码:

        buffer = StringIO.StringIO()
        status = subprocess.call(args, stdout=log_fps["trace"], stderr=buffer)

        if status and self.V_LEVEL:
            sys.stderr.write(buffer.getvalue())
            print "generated error"

        if status:
            log_fps["fail"].write("==> Error with files %s and %s\n" % (domain_file, problem_file))
            log_fps["fail"].write(buffer.getvalue())

我收到以下错误:

Traceback (most recent call last):
  File "./runit.py", line 284, in <module>
    launcher.run_all_cff_domain_examples("ring")
  File "./runit.py", line 259, in run_all_cff_domain_examples
    result = self.run_clg(in_d["domain"], in_d["problem"], in_d["prefix"])
  File "./runit.py", line 123, in run_clg
    status = subprocess.call(args, stdout=log_fps["trace"], stderr=buffer)
  File "/usr/lib/python2.7/subprocess.py", line 493, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/usr/lib/python2.7/subprocess.py", line 672, in __init__
    errread, errwrite) = self._get_handles(stdin, stdout, stderr)
  File "/usr/lib/python2.7/subprocess.py", line 1075, in _get_handles
    errwrite = stderr.fileno()
AttributeError: StringIO instance has no attribute 'fileno'

我想这意味着我无法使用StringIO在内存中收集stderr。除了写入/ tmp中的文件外,我还能做些什么?

2 个答案:

答案 0 :(得分:2)

stdout = subprocess.check_output(args)

有关更多选项,请参阅check_output文档。

如果您不想捕获stdout,请使用Popen.communicate

from subprocess import Popen, PIPE

p = Popen(args, stdout=log_fps["trace"], stderr=PIPE)
_, stderr = p.communicate()

答案 1 :(得分:0)

import subprocess

p = subprocess.Popen(args, stdout=log_fps["trace"], stderr=subprocess.PIPE)

_, stderr = p.communicate()
print stderr,