相当于Python中的BASH XTRACEFD重定向

2024-10-03 15:30:19 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在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执行行上执行

谢谢!:)


Tags: 文件命令脚本bashthattracecodeexport
1条回答
网友
1楼 · 发布于 2024-10-03 15:30:19

根据你的描述:

I need the trace to be run inside the script so I could redirect it to a file

$ python -m trace -t prog.py

这将把跟踪结果输出到stdout中,我想您应该将该结果存储到文件中。下面是一个基于official documentation的例子。你知道吗

程序副本

def main():
    pass

if "__main__" == __name__:
    main()

跟踪_运行.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

程序封面

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

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

相关问题 更多 >