【问题标题】:How to write log and print to screen at the same time? [duplicate]如何同时写入日志和打印到屏幕? [复制]
【发布时间】:2021-03-12 15:39:19
【问题描述】:

我正在编写构建脚本。我想记录正在发生的所有事情,但我也想在它运行时查看所有内容。 这样做的最佳做法是什么?

【问题讨论】:

  • 据我了解,这只是记录到文件中,但不会打印到屏幕上。我错过了什么吗?
  • 它记录到无论你设置什么,你可以有多个处理程序,例如一个文件(旋转或其他),一个流,...
  • 你有例子吗?我尝试了 logging.addHandler,但这似乎不起作用。
  • 文档有几个例子,并且有很多关于 SO 的问题和其他地方的文章涵盖了这个主题。如果在研究之后你仍然有一个特定的问题,edit 给一个minimal reproducible example

标签: python logging runtime


【解决方案1】:

我会推荐使用 tee 命令将输出保存到文件

只需在 python 脚本中编写 print 语句并将内容传递给 tee 命令

Tee 命令捕获 std in 并打印并将其写入文件。

例如控制台内容将保存到 build.log

Linux $ your_buildscript.py 2>&1 | tee build.log

窗户

your_buildscript.py | tee build.log

参考: Linux tee:https://man7.org/linux/man-pages/man1/tee.1.html

windows tee:https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/tee-object?view=powershell-7.1

【讨论】:

    猜你喜欢
    • 2012-03-08
    • 2021-08-17
    • 2019-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多