Python 错误日志记录
我想找到一种方法来记录强制 python 解释器退出以保存到文件并打印到屏幕上的每个错误。我想这样做的原因是我想统计我在编写代码时所犯的错误类型,着眼于找到避免我将来经常犯的错误的方法。
我一直在尝试通过使用 subprocess 模块为 python 解释器编写包装器来做到这一点。基本上,它运行 python 解释器,捕获任何输出,解析并将其保存到文件中,打印输出,并使用 matplotlib 制作一些摘要图。但是,我在实时从包装器脚本获取输出时遇到问题。例如,如果我正在运行的脚本是:
import os
import time
for x in range(10):
print "testing"
time.sleep(10)
并且我将 subprocess.Popen() 与 p.communicate() 一起使用,则包装器将等待 100 秒,然后打印所有输出。我希望包装器尽可能不可见 - 理想情况下,在这种情况下,它会每十秒打印一次“testing”。
如果有人能指出我这样做的好方法,我将不胜感激。
谢谢!
I'd like to find a way to log every error that forces the python interpreter to quit to be saved to a file as well as being printed to the screen. The reason I would like to do this is that I want to keep stats on the types of errors I make while writing code, with an eye towards finding ways to avoid mistakes I make commonly in the future.
I've been attempting to do this by writing a wrapper for the python interpreter using the subprocess module. Basically, it runs the python interpreter, captures any output, parse and saves it to a file, prints the output, and use matplotlib to make some summary figures. However, I'm having a problem getting output from my wrapper script in real time. For example, if the script I'm running is:
import os
import time
for x in range(10):
print "testing"
time.sleep(10)
and I'm using subprocess.Popen() with p.communicate(), the wrapper will wait 100 seconds, and then print all of the output. I'd like the wrapper to be as invisible as possible - ideally in this case it would print "testing" once every ten seconds.
If someone could point me towards a good way of doing this, I'd greatly appreciate it.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信你可以简单地用你自己的函数替换 sys.excepthook 。您可以在 Python 文档 中阅读相关内容。
基本上,它允许您自定义当异常渗透到强制 Python 解释器退出时会发生什么。您可以这样使用它:
您可能还想查看回溯模块,用于格式化您获得的回溯。
I believe you can simply replace
sys.excepthook
with your own function. You can read about it in the Python documentation.Basically, it allows you to customize what happens when an exception percolates up to the point of forcing the Python interpreter to quit. You use it like this:
You'll probably also want to look at the traceback module, for formatting the traceback you get.