将打印重定向到日志文件
好的。我已经完成了我的第一个Python程序。它有大约1000行代码。 在开发过程中,我在使用 os.system() 运行命令之前放置了大量的 print 语句 可以这样说,“
print "running command",cmd
os.system(cmd)
现在我已经完成了程序”。我考虑过对它们进行评论,但将所有这些不必要的打印(我无法删除所有 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)
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(10)
您应该看一下 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")
生成一个名为“的文件”日志文件”,内容为:
2012-10-18 06:40:03,582 INFO hello
下次,如果您从一开始就使用
logging
模块而不是使用print
语句,您会更高兴。它提供了您想要的控件,并且您可以将其写入到标准输出,而这仍然是您想要的位置。这里很多人建议重定向标准输出。 这是一个丑陋的解决方案。它改变了全局,更糟糕的是,它改变了它以供这个模块使用。我会尽快制作一个正则表达式,将所有
print foo
更改为print >>my_file, foo
并将my_file
设置为 stdout 或实际的我选择的文件。- 如果应用程序的任何其他部分实际上依赖于写入标准输出(或者将来会这样,但你还不知道),这会破坏它们。即使您不这样做,如果您错过了顶部的一小行,它也会使读取您的模块看起来像是在做一件事,但实际上它在做另一件事。
- V 形打印相当难看,但远没有临时更改进程的
sys.stdout
难看。 - 从技术上讲,正则表达式替换无法正确执行此操作(例如,如果您位于多行字符串文字中,它可能会产生误报)。不过,它很容易发挥作用,只要留意它即可。
os.system
实际上总是不如使用subprocess
模块。后者不需要调用 shell,不会以通常不需要的方式传递信号,并且可以以非阻塞方式使用。
使用日志记录模块重定向 stdout 和 stderr 的简单方法如下:
如何复制sys.stdout 到 python 中的日志文件?
您可以将 sys.stdout 重定向为与 sys.stdout 具有相同接口的任何对象,在该对象的写入中,您也可以打印到终端和文件。例如,请参阅此食谱 http://code.activestate.com/recipes/119404-print -钩子/
有很多方法可以将输出写入“.log”文件。
日志记录是跟踪某些文件运行时发生的事件的一种方法。也表明某些事件已经发生。
import logging
logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)
logging.debug('This is debug message')
logging.info('This is information message')
logging.warning('This is warning message')
logging.error('This is warning message')
另一种方法可以用来减少所有这些事情,只要您打印到控制台,所有内容都将保存到“日志”文件中,
python abc.py > abc.log
通过使用此方法,您可以将所有内容写入日志文件
只是关于附加模式与写入模式的注释。如果您希望它替换日志文件,请将文件模式更改为“w”。我还必须注释掉该流。然后使用logging.info()输出到指定的文件。
if __name__ == '__main__':
LOG_FORMAT = '%(asctime)s:%(levelname)s ==> %(message)s'
logging.basicConfig(
level=logging.INFO,
filename="logfile",
filemode="w",
format=LOG_FORMAT
#stream=sys.stdout
)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
Python 允许您捕获并分配 sys.stdout(如上所述)来执行此操作:
Python lets you capture and assign sys.stdout - as mentioned - to do this: