python - Python 记录通过命令提示符的所有内容
问题描述
我正在尝试记录通过我的命令提示符的所有内容。这包括由 python 脚本启动的批处理脚本输出。
如果我像这样运行我的python文件
python logEverything.py >> logFile.txt
它给了我我想要的东西,而在命令提示符下打印的所有内容都将被放入该文件中。
问题在于它不再在命令提示符中显示任何内容。此外,我希望能够在程序内部指定日志文件路径。
那么有没有办法使用 Python记录通过命令提示符的所有内容?兼容windows和Linux?
所以 logEverything.py 会是这样的
import sys
def main():
import io
old_stdout = sys.stdout # Memorize the default stdout stream
sys.stdout = buffer = io.StringIO()
print('Log test')
os.system('this is a test')
print('More logging')
#Finished -> put everything into log_file.txt
sys.stdout = old_stdout
whatWasPrinted = buffer.getvalue()
print(whatWasPrinted) # Why not to print it?
buffer.close()
此解决方案部分有效,但未捕获 os.system() 的输出
解决方案
从askubuntu 上的这个问题:
command |& tee -a output.txt
标准输出和标准错误流都将被复制到文件中,同时在终端中仍然可见。如果文件已存在,则新数据将附加到文件末尾。
所以你可以使用python logEverything.py |& tee -a logFile.text
推荐阅读
- c - LeetCode:解决消毒剂违规问题
- julia - 朱莉娅圆形包含
- python - 有没有办法在 tkinter 中删除特定的网格元素?
- python-3.x - 如何判断 SQlite3 数据库中是否已存在多个值,Python3
- dynamics-crm - 如何过滤 CDS(powerapps) 中的数据以限制未经授权的用户
- typescript - typescript 中“declare module name_without_quotes”类型的声明的目的是什么(与带引号的名称相比)
- javascript - Javascript getParams 破坏 JSON
- c# - Blazor 的问题
- flutter - 使用小部件属性 VS 在状态类上接受参数
- c# - asp.net core 2.2,无论 gitignore 中是否存在 appsettings.json 都更新为 azure devops