相当于Python中的BASH_XTRACEFD重定向

时间:2016-11-14 10:15:02

标签: python bash python-2.7

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

exec 3> >(sed -e 's/^[+]* /[BASH] /' >> code_that_ran.tmp) 
export BASH_XTRACEFD=3
set -x

我尝试了什么:

$ python -m trace -t prog.py

问题是我需要在脚本中运行跟踪,这样我就可以将它重定向到一个文件,对它执行一些逻辑,而不是如上所述在python执行行上

感谢:!)

1 个答案:

答案 0 :(得分:1)

根据你的描述:

  

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

$ python -m trace -t prog.py

这会将跟踪结果输出到stdout,我想你想将结果存储到文件中。以下是基于official documentation的示例。

<强> prog.py

def main():
    pass

if "__main__" == __name__:
    main()

<强> trace_run.py

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_run.py prog.py

<强> prog.cover

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

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