捕获python3中子进程的所有输出

时间:2017-02-16 15:16:28

标签: python-3.x svn terminal subprocess capture

我想将所有输出捕获到子进程打印出来的变量中。这是我的代码:

#!/usr/bin/env python3

import subprocess # Subprocess management
import sys # System-specific parameters and functions

try:
    args = ["svn", "info", "/directory/that/does/not/exist"]
    output = subprocess.check_output(args).decode("utf-8")
except subprocess.CalledProcessError as e:
    error = "CalledProcessError: %s" % str(e)
except:
    error = "except: %s" % str(sys.exc_info()[1])
else:
    pass

此脚本仍会将其打印到终端:

  

svn:E155007:'/ directory / that / does / not / exist'不是工作副本

如何将其捕获到变量中?

1 个答案:

答案 0 :(得分:2)

check_output仅捕获stdout和NOT stderr(根据https://docs.python.org/3.6/library/subprocess.html#subprocess.check_output

为了捕获stderr,你应该使用

>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT, ...)

我建议在顺便提一下之前阅读文档。