-1

filename and line number of python script

I need to print the current filename, function and line number in a Cython script. The proposed solutions only work for .py script and they do NOT work for Cython script.

Thank you

q0987
  • 34,938
  • 69
  • 242
  • 387

1 Answers1

1

This is a pretty unsatisfactory work-round, but I suspect it's probably (close to) the best you can do.

Cython generates debugging info when an exception is raised, therefore you need to raise and catch and exception to get access to this info

import sys
import traceback

def f():
    # code ...
    try:
        raise RuntimeError() # get information about this line
    except RuntimeError:
        print(traceback.extract_tb(sys.exc_info()[2],limit=1))
    # ... more code

Note that you can't attempt to save duplication by putting this all in a "get_debug_info" function and then looking further up the stack trace - Cython only generates the stack frame for a function as the exception propagates up the stack so if you catch the exception then you can't see any Cython frames above it.

DavidW
  • 29,336
  • 6
  • 55
  • 86