python - 在批处理文件中运行 python 时,如何将 python 打印输出保存为文本

标签 python batch-file printing save

我当前正在批处理文件中运行 python 脚本。在Python中,我有一些打印函数来监视正在运行的代码。打印的信息将显示在命令窗口中。同时,我还想将所有这些打印输出文本保存到日志文件中,以便我可以长期跟踪它们。

目前,要做到这一点,我需要在 python 中拥有 print 函数并使用 text.write 函数写入文本文件。这给维护带来了一些麻烦,因为每次更改一些打印文本时,我也需要更改写入功能中的文本。而且我觉得这不是最有效的方法。

例如:

start_time = datetime.now()
print("This code is run at " + str(start_time) + "\n")
log_file.write("This code is run at " + str(start_time) + "\n")

我想使用python中的打印功能,这样我就可以在命令窗口中看到它,然后将所有打印输出信息一次性保存到日志文件中。

最佳答案

从长远来看,为了获得更好的解决方案,请考虑内置 logging module 。您可以指定多个目标,例如标准输出和文件、日志轮换、格式设置和重要性级别。

示例:

import logging
logging.basicConfig(filename='log_file', filemode='w', level=logging.DEBUG)

logging.info("This code is run at %", start_time)

关于python - 在批处理文件中运行 python 时,如何将 python 打印输出保存为文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57417939/

相关文章:

Python 打印 "<built-in method ... object"而不是列表

python - 训练神经网络时,Tensorflow 完成后是否会自动恢复到最佳时期?

python - TensorFlow 您必须使用 dtype float 为占位符张量 'Placeholder_2' 提供一个值

python - 从 Python : Pipe Stata console output to command line 调用的 Stata 批处理

C++系统函数

该命令的语法批量不正确?

python - 使用 Scapy 解析 PPPoE 标签

php - 将网站导出到 XML 页面

c# - 打印到点阵打印机

javascript - JavaFX : Set default printer for WebEngine/Webview