Python中BASH_XTRACEFD重定向的等价物

Python中BASH_XTRACEFD重定向的等价物,python,bash,python-2.7,Python,Bash,Python 2.7,如何在Python2.7中模拟下面的BASH脚本?(重定向运行到某个文件的命令): 我尝试的是: $ python -m trace -t prog.py 问题是我需要在脚本内部运行跟踪,这样我就可以将它重定向到一个文件,对它执行一些逻辑,而不是像上面所说的那样在python执行行上执行 谢谢!:) 根据您的描述: 我需要在脚本中运行跟踪,以便将其重定向到文件 这将把跟踪结果输出到标准输出中,我想您希望将该结果存储到文件中。下面是一个基于的示例 prog.py def main():

如何在Python2.7中模拟下面的BASH脚本?(重定向运行到某个文件的命令):

我尝试的是:

$ python -m trace -t prog.py
问题是我需要在脚本内部运行跟踪,这样我就可以将它重定向到一个文件,对它执行一些逻辑,而不是像上面所说的那样在python执行行上执行


谢谢!:)

根据您的描述:

我需要在脚本中运行跟踪,以便将其重定向到文件

这将把跟踪结果输出到标准输出中,我想您希望将该结果存储到文件中。下面是一个基于的示例

prog.py

def main():
    pass

if "__main__" == __name__:
    main()
import sys
import trace
import imp

# create a Trace object, telling it what to ignore, and whether to do tracing or line-counting or both.
tracer = trace.Trace(
    ignoredirs=[sys.prefix, sys.exec_prefix],
    trace=0,
    count=1)

# load target program dynamically
target = imp.load_source(sys.argv[1], './'+sys.argv[1])

# run the main function of program using the given tracer
tracer.runfunc(target.main)

# make a report, placing output in the current directory
r = tracer.results()
r.write_results(show_missing=True, coverdir=".")
trace_run.py

def main():
    pass

if "__main__" == __name__:
    main()
import sys
import trace
import imp

# create a Trace object, telling it what to ignore, and whether to do tracing or line-counting or both.
tracer = trace.Trace(
    ignoredirs=[sys.prefix, sys.exec_prefix],
    trace=0,
    count=1)

# load target program dynamically
target = imp.load_source(sys.argv[1], './'+sys.argv[1])

# run the main function of program using the given tracer
tracer.runfunc(target.main)

# make a report, placing output in the current directory
r = tracer.results()
r.write_results(show_missing=True, coverdir=".")
然后只需运行
python trace\u run.py prog.py

节目封面

>>>>>> def main():
    1:     pass

>>>>>> if "__main__" == __name__:
>>>>>>     main()