问题描述
好的.我已经完成了我的第一个 python 程序.它有大约 1000 行代码.在开发过程中,我在使用 os.system()
运行命令之前放置了大量 print
语句说些类似的话,
Okay. I have completed my first python program.It has around 1000 lines of code.During development I placed plenty of print
statements before running a command using os.system()
say something like,
print "running command",cmd
os.system(cmd)
现在我已经完成了程序.我考虑过评论它们,但将所有这些不必要的打印(我无法删除所有 print
语句 - 因为有些为用户提供有用的信息)重定向到日志文件中会更有用吗?任何技巧或提示.
Now I have completed the program. I thought about commenting them but redirecting all these unnecessary print (i can't remove all print
statements - since some provide useful info for user) into a log file will be more useful? Any tricks or tips.
推荐答案
Python 允许您捕获和分配 sys.stdout - 如前所述 - 来执行此操作:
Python lets you capture and assign sys.stdout - as mentioned - to do this:
import sys
old_stdout = sys.stdout
log_file = open("message.log","w")
sys.stdout = log_file
print "this will be written to message.log"
sys.stdout = old_stdout
log_file.close()
这篇关于重定向打印到日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!