Python get the line number of the execution code, where the code is on the string format

34 views Asked by At

I want to get the line of the execution code, but the code is in the string format. I tried using Python's trace module, but the results were not what I expected. Here is the code:

import trace
    
# Sample code to analyze
code = """
def unused_function():
  print("hello world!")
    
def main():
  a = 1
  b = 2
  c = 4
  d = a + c
  print(d)
if __name__ == '__main__':
  main()

....

def do_exec(x):
  return exec(x)

tracer = trace.Trace(trace=1, count=0)
tracer.run('do_exec(code)')
res = tracer.results()

And here I got:

 --- modulename: temp_code, funcname: <module>
<string>(1):  --- modulename: temp_code, funcname: do_exec
temp_code.py(19):   return exec(x)
 --- modulename: temp_code, funcname: <module>
<string>(2): <string>(5): <string>(11): <string>(12):  --- modulename: temp_code, funcname: main
<string>(6): <string>(7): <string>(8): <string>(9): <string>(10): 5

What I want is:

11
12
5
6
7
8
9
10

So, I tried to use res.counts but I got None. Can you help me?

0

There are 0 answers