Python stack traceback - need a 'list of list' to be available for specific trace functionality

Viewed 25

I am trying to extract stack trace in python to have some controlled tracing. I get required array / tuples to work with in version 2.7 as below

[('a1.py', 11, '<module>', 'fun1()'), ('a1.py', 10, 'fun1', 'fun2()'), ('a1.py', 5, 'fun2', 'tx = traceback.extract_stack();')]
[('a1.py', 12, '<module>', 'fun2()'), ('a1.py', 5, 'fun2', 'tx = traceback.extract_stack();')]

But in version 3.6 the output is

[<FrameSummary file a1.py, line 11 in <module>>, <FrameSummary file a1.py, line 10 in fun1>, <FrameSummary file a1.py, line 5 in fun2>]
[<FrameSummary file a1.py, line 12 in <module>>, <FrameSummary file a1.py, line 5 in fun2>]

For my controlled trace functionality in v 3.6, require the output to be as is provided in v 2.7. Request for any guidance / help on this. Below is code used

import traceback
def fun2 () : 
    tx = traceback.extract_stack();
    print(tx)
def fun1 (): 
    si = 'Hello'
    fun2()

fun1()
fun2()
1 Answers

You can extract the information from the FrameSummary object:

def fun2():
    tx = traceback.extract_stack()
    extracted = [(fs.filename, fs.lineno, fs.name, fs.line) for fs in tx]
    print(extracted)

Result:

[('main.py', 15, '<module>', 'fun1()'), ('/main.py', 12, 'fun1', 'fun2()'), ('main.py', 5, 'fun2', 'tx = traceback.extract_stack()')]

Related