【问题标题】:How to capture the terminal log of script to a file? [duplicate]如何将脚本的终端日志捕获到文件中? [复制]
【发布时间】:2017-10-24 06:55:23
【问题描述】:

我有一个从 Linux 终端成功运行的 python 脚本。当我运行 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 打印到一个输出文件。

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

【问题讨论】:

  • “捕获整个终端输出”是什么意思?上面的代码确实已经将所有内容写入outfile。虽然使用contextlib.redirect_(stdout|stderr) 会更容易。
  • @YSelf 我的代码仅将print 语句打印到文件中,我希望将所有显示在terminal 上的日志记录也包括在内

标签: python linux stdout stderr


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-15
      • 2022-09-23
      • 2019-05-09
      • 2020-02-28
      • 2019-07-28
      • 1970-01-01
      相关资源
      最近更新 更多