Python 跟踪模块 - 在执行时跟踪行,但保存到文件,而不是标准输出 [英] Python trace module - Trace lines as they are executed, but save to file, rather than stdout
问题描述
我想在 Python 脚本执行时跟踪它们的行.但是我使用的程序需要将内容打印到标准输出.python 跟踪模块的跟踪选项将它们打印到标准输出.是否可以告诉它不要将它们打印到标准输出,而是将它们保存到文件中?我尝试设置 outfile
参数,但它不会停止打印跟踪线.
I want to trace the lines of a python script as they are executed. However the programme I use needs to print things to stdout. The trace option to the python trace module prints them to stdout. Is there anwyay to tell it to not print them to stdout, but instead save them to a file? I tried setting the outfile
parameter, but it doesn't stop the printing of trace lines.
推荐答案
您可以复制跟踪模块代码,并进行一些更改以将其输出写入您选择的文件.在第 600 行和第 650 行之间有五个 print
语句是您要更改的语句.因为你不需要让它太漂亮,你可以将它添加到文件的最后:
You could copy the trace module code, and make a few changes to get it to write its output to a file of your choosing. There are five print
statements between lines 600 and 650 that are the ones you want to change. Since you don't need to make it too pretty, you can add this to the very end of the file:
my_out_file = open("/home/mytrace.txt", "w")
并更改打印语句:
print "%s(%d): %s" % (bname, lineno,
linecache.getline(filename, lineno)),
变成这样:
print >>my_out_file, "%s(%d): %s" % (bname, lineno,
linecache.getline(filename, lineno)),
这篇关于Python 跟踪模块 - 在执行时跟踪行,但保存到文件,而不是标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!