这个问题已经有了答案:
How to capture stdout output from a Python function call?
2个答案
我有一个从linux终端成功运行的python
脚本。运行shell script
脚本时,我可以使用python
将终端输出收集到文件中。
现在我要从python script
本身收集终端输出。但做不到。
我只想使用python
而不使用任何shell
或unix
脚本
我在我的python file
中做了如下工作:
class Tee(object):
def __init__(self, f1, f2):
self.f1, self.f2 = f1, f2
def write(self, msg):
self.f1.write(msg)
self.f2.write(msg)
outfile = open('outfile', 'w')
sys.stdout = outfile
sys.stderr = Tee(sys.stderr, outfile)
python file
中的这部分代码同时将stderr
和stdout
打印到输出文件。如何将整个终端输出捕获到单个文件。
最佳答案
如果您同意在python
中包含PATH
的要求,那么我将调用另一个python进程来运行您的主脚本。
在顶级脚本中,使用subprocess.Popen
在子进程中启动所需的脚本。然后使用subprocess.Popen.communicate()
从进程获取输出流(并可能向进程传递任何命令行参数)。
您甚至可以使用popen将所有std*输出重定向到文件,但这实际上取决于您的需要和其他方面。communicate()
对于您可能想要做的事情似乎非常有用。
subprocess.Popen
subprocess.Popen.communicate