2016-11-14 113 views
1

如何在Python2.7中模擬以下BASH腳本? (跑一些文件的命令重定向):等效於Python中的BASH_XTRACEFD重定向

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

我的嘗試:

$ python -m trace -t prog.py 

問題是我需要跟蹤腳本內部運行,所以我可以把它重定向到一個文件,它蟒執行行執行一些邏輯和不高於

感謝爲說:)

回答

1

根據你的描述:

我需要跟蹤腳本內部運行,所以我可以把它重定向到一個文件

$ python -m trace -t prog.py 

這將輸出跟蹤結果到標準輸出,我想你要存儲結果到文件中。以下是基於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()