Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Change linenumber and filename printed in exceptions like #line in C
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
But this resulted in the output
Traceback (most recent call last): File "", line 4, in <module> frame.f_lineno=1000 ValueError: f_lineno can only be set by a trace function
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 and executes this file. This works fine, but obviously exceptions show the linenumber in and not the linenumber in the original files.
They're called dunders (double underscore) in python list here:
for exceptions, you can examine the call stack
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 "" line 10 ...'] with the correct line and file reference. This supposes that you store these position informations in a separate file when you create

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Group files according to first few characters in filename python_newbie09 7 160 Aug-02-2019, 06:34 AM
Last Post: cvsae
  multi-line messages in raised exceptions? Skaperen 3 120 Aug-01-2019, 02:17 AM
Last Post: Skaperen
  How to change existing date to current date in a filename? shankar455 1 248 Apr-17-2019, 01:53 PM
Last Post: snippsat
  print number of a list line per line lateublegende 2 274 Mar-20-2019, 04:07 PM
Last Post: lateublegende
  Creating custom exceptions that co-operate LadySvetlana 4 306 Mar-19-2019, 04:24 PM
Last Post: LadySvetlana
  Putting an array for each string that is printed to a loop ClaudioSimonetti 1 257 Feb-05-2019, 12:52 PM
Last Post: perfringo
  Catching exceptions in embedded code no longer works on 3.7.2? FFMG 5 331 Feb-02-2019, 10:15 AM
Last Post: Larz60+
  Adding new line in a one line txt file. Mady 7 565 Nov-21-2018, 01:04 PM
Last Post: Gribouillis
  Rename only first 4 characters of filename bmatt8 2 427 Nov-15-2018, 05:15 PM
Last Post: nilamo
  generate filename of value and extend Marre 2 445 Oct-01-2018, 07:31 PM
Last Post: Larz60+

Forum Jump:

Users browsing this thread: 1 Guest(s)