Change linenumber and filename printed in exceptions like #line in C - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Change linenumber and filename printed in exceptions like #line in C (/thread-19714.html) |
Change linenumber and filename printed in exceptions like #line in C - kryptomatrix - Jul-11-2019 Hi, As you might know, there is the #line command in the C-preprocessor: #include <stdio.h> #line 20 "abc" int main() { printf("%i %s\n", __LINE__, __FILE__); //outputs 22 abc }Is there something like this #line command in python? I want to change what is printed in exceptions. I tried: import inspect frame = inspect.currentframe() fileNo = frame.f_lineno frame.f_lineno=1000But this resulted in the output In case you were wondering why I would want to change the filename and filenumber: In my workflow, I have a files that contain python source code and other text. A script searches those python source code blocks, puts them into the right order, writes them into a file (called sum.py) and executes this file. This works fine, but obviously exceptions show the linenumber in sum.py and not the linenumber in the original files.
RE: Change linenumber and filename printed in exceptions like #line in C - Larz60+ - Jul-12-2019 They're called dunders (double underscore) in python list here: https://docs.python.org/3/reference/import.html?highlight=__name__#__name__ for exceptions, you can examine the call stack see: https://python-forum.io/Thread-Walking-the-python-call-stack-without-leaks?highlight=stack RE: Change linenumber and filename printed in exceptions like #line in C - Gribouillis - Jul-12-2019 I don't think there is any equivalent of the #line preprocessing directive in python. What you could do is catch the exception and transform the output of traceback.format_tb() by replacing items such as ['File "sum.py" line 10 ...'] with the correct line and file reference. This supposes that you store these position informations in a separate file when you create sum.py.
|