Skip to main content
 首页 » 编程设计

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

2024年11月01日10lyj

我试图在内存中收集 stderr,而不是直接将其写入文件或标准输出。我这样做是为了以某种方式生成错误日志文件。我找到了一个名为 StringIO 的图书馆那是一个内存中的"file"。我不认为它能解决问题。这是我的代码:

        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 中的文件之外,我还能做什么?

请您参考如下方法:

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()