获得调用函数的标准输出

Posted by kifish on April 29, 2018

获得所调用的函数的标准输出,比如print()等。见SO: https://stackoverflow.com/questions/16571150/how-to-capture-stdout-output-from-a-python-function-call

a.by

import io
from contextlib import redirect_stdout

f = io.StringIO()
with redirect_stdout(f):
    do_something(my_object)
out = f.getvalue()

注意下面的subprocess返回的输出是bytes,转换成str还需要decode. 上面的方法也是返回的bytes
getvalue() Return bytes containing the entire contents of the buffer.
-https://docs.python.org/3/library/io.html

这种方法似乎影响不到重定向之后的log?假设要执行的函数在b.py中,并且在b.py中把log重定向到了stdout,但是在a.by中没有得到log的输出。 在a.py中把b.py中的log重定向也复制一份,还是不work.

获得某个python程序的stdout,用子进程即可实现。

import subprocess
import shlex
shell_cmd = 'python main.py'
cmd = shlex.split(shell_cmd)
p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE)