2

we have a python script that uses a c library to call some low level functions. Because of code structure reasons we want to store the stack trace/call stack before each c call.

To do this we use traceback.extract_stack() to extract the call stack of python. When an exception occurs later on, we use traceback.format_list(abc) on each element to format and print the stack trace.

The problem is that the function extract_stack is too slow. I slows down our code from 1.7 seconds to 11 seconds.

Is there any function to store the stack trace in order to be able to use/print it later? The stacktrace getter must be very fast. The format function can be slow, this is no problem.

Example:

Stack Trace:
  - LXScript: '_LXS:TOOL:RUNLX'
      File "_LXS:TOOL:RUNLX", line 13, in <module>
      File "lxs", line 1, in <module>
  - UNIFACE ACTIVATE: 'ACTQREC_SVC' 'EXECLXSRP'
  - LXScript: '_DATATRT:ACTQREC:EXECUTE@Main:run'
      File "_LXS:TOOL:RUNLX", line 13, in <module>
      File "lxs", line 1, in <module>
      File "<string>", line 63, in run
      File "<string>", line 97, in __doAll
      File "<string>", line 127, in __do
      File "_DATATRT:ACTQREC:EXECUTE", line 7, in do
  - UNIFACE ACTIVATE: 'ACTQ_CSVC' 'EXECBYREC'
  - LXScript: 'TOOL:ACTQ:SYNLAB_DATA@Main:runOnBeforeExec'
      File "TOOL:ACTQ:SYNLAB_DATA", line 1, in <module>
    ImportError: No module named 'localls'
5
  • 1
    Why not get the stack trace after the exception, so the overhead is only in exceptional circumstances? Commented Jan 5, 2017 at 10:01
  • maybe you could use the limit parameter to only get a part of the context. In the example above, maybe you don't need all the stack but only the 5 deeper calls. Should speed up operations a bit. Commented Jan 5, 2017 at 10:05
  • @PeterWood Because we don't have the exsiting stacktrace when we enter the c interface from the non python code (uniface). Commented Jan 5, 2017 at 12:01
  • @Jean-FrançoisFabre I think this will still be too slow. Commented Jan 5, 2017 at 12:02
  • By using a limit of 2, I come to 2,1 seconds. Compared to 1,7 and 11 it makes a big difference!! Commented Jan 5, 2017 at 12:10

1 Answer 1

3

I resolved the problem!!!

We can use stt_obj = sys._getframe().f_back to get the "<frame>?" And then we can use estt_obj = traceback.extract_stack(f=stt_obj) and traceback.format_list(estt_obj) to get the stack trace as string list.

Sign up to request clarification or add additional context in comments.

2 Comments

Could you show where elem and self exist to read STT_OBJ?
Fantastic thank you - this really works, f is a frame! I wish that was clearer in the docs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.