web*_*org 29 python printing logging
好的.我已经完成了我的第一个python程序.它有大约1000行代码.在开发期间,我print在运行命令之前放置了大量语句,os.system()
例如,
print "running command",cmd
os.system(cmd)
Run Code Online (Sandbox Code Playgroud)
现在我已经完成了这个计划.我考虑过对它们进行评论,但重定向所有这些不必要的打印(我无法删除所有print语句 - 因为有些语句为用户提供有用的信息)到日志文件中会更有用吗?任何技巧或提示.
小智 49
你应该看看python日志记录模块
编辑:示例代码:
import logging
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG, filename="logfile", filemode="a+",
format="%(asctime)-15s %(levelname)-8s %(message)s")
logging.info("hello")
Run Code Online (Sandbox Code Playgroud)
使用内容生成名为"logfile"的文件:
2012-10-18 06:40:03,582 INFO hello
Run Code Online (Sandbox Code Playgroud)
Mic*_*ael 45
Python允许您捕获并分配sys.stdout - 如上所述 - 执行此操作:
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()
Run Code Online (Sandbox Code Playgroud)
下一次,如果不是使用print语句而是logging从头开始使用模块,那么你会更高兴.它提供了你想要的控件,你可以让它写入stdout,而它仍然在你想要的地方.
这里有很多人建议重定向stdout.这是一个丑陋的解决方案.它改变了全局性 - 更糟糕的是 - 它为这个模块的使用而改变了它.我会更快地创建一个正则表达式,将所有内容更改print foo为print >>my_file, foo设置my_file为stdout或我选择的实际文件.
sys.stdout过程那样难看.os.system几乎总是不如使用该subprocess模块.后者不需要调用shell,不以通常不需要的方式传递信号,并且可以以非阻塞方式使用.
小智 5
您可以创建日志文件并准备写入。然后创建一个函数:
def write_log(*args):
line = ' '.join([str(a) for a in args])
log_file.write(line+'\n')
print(line)
Run Code Online (Sandbox Code Playgroud)
然后用 write_log() 替换你的 print() 函数名