Reputation: 98
How can I emulate the following BASH script in Python2.7 ? (Redirection of commands that ran to some file):
exec 3> >(sed -e 's/^[+]* /[BASH] /' >> code_that_ran.tmp)
export BASH_XTRACEFD=3
set -x
What I tried:
$ python -m trace -t prog.py
Problem is I need the trace to be run inside the script so I could redirect it to a file, perform some logic on it and not on the python execution line as said above
Thanks!:)
Upvotes: 1
Views: 120
Reputation: 3080
According to your description:
I need the trace to be run inside the script so I could redirect it to a file
$ python -m trace -t prog.py
This will output trace result into stdout, I suppose you want to store that result into file. Below is an example based on the 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=".")
then simply run python trace_run.py prog.py
prog.cover
>>>>>> def main():
1: pass
>>>>>> if "__main__" == __name__:
>>>>>> main()
Upvotes: 1