将打印重定向到日志文件 [英] redirect prints to log file
问题描述
好的.我已经完成了我的第一个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()
这篇关于将打印重定向到日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!