我当前正在批处理文件中运行 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/