如何将脚本的终端日志捕获到文件中



我有一个python脚本,它可以从Linux终端成功运行。当我运行python脚本时,我能够使用shell script将终端输出收集到文件中。

现在我想从python script本身收集终端输出。但无法做到这一点。

我想只使用python而不使用任何shellunix脚本来做到这一点

我在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中的这部分代码将stderrstdout打印到输出文件。

如何将整个终端输出捕获到单个文件中。

如果你同意在你的PATH中有python的要求,那么我会调用另一个python进程来运行你的主脚本。

在顶级脚本中,使用 subprocess.Popen 在子进程中启动所需的脚本。然后使用 subprocess.Popen.communicate() 从进程中获取输出流(并可能将任何命令行参数传递到进程中)。

您甚至可以仅使用 Popen 将所有 std* 输出重定向到文件,但这实际上取决于您的需求等等。 communicate()似乎对您可能想要做的事情非常有用。

  • 子流程。普彭
  • 子流程。Popen.communication.communication

你可以在代码中使用这样的东西: os.system('pdv -t %s > 123.txt' % epoch_name)你也可以看看这个: 子流程

最新更新