我有一个python
脚本,它可以从Linux终端成功运行。当我运行python
脚本时,我能够使用shell script
将终端输出收集到文件中。
现在我想从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
打印到输出文件。
如何将整个终端输出捕获到单个文件中。
如果你同意在你的PATH
中有python
的要求,那么我会调用另一个python进程来运行你的主脚本。
在顶级脚本中,使用 subprocess.Popen
在子进程中启动所需的脚本。然后使用 subprocess.Popen.communicate()
从进程中获取输出流(并可能将任何命令行参数传递到进程中)。
您甚至可以仅使用 Popen 将所有 std* 输出重定向到文件,但这实际上取决于您的需求等等。 communicate()
似乎对您可能想要做的事情非常有用。
- 子流程。普彭
- 子流程。Popen.communication.communication
你可以在代码中使用这样的东西: os.system('pdv -t %s > 123.txt' % epoch_name)
你也可以看看这个: 子流程