hanugm
hanugm

Reputation: 1397

How to print file path and line number while program execution?

I am running a Python program and I am getting an error. The program is written by someone.

The program has a lot of classes, methods, loops etc.,

Assume that I got an error, the error reporting in Python contains the line number and the nested call information and ends with key error.

I want something like this:

While the program executes, the output, which I can see in terminal, should contain the filename (or path of the file) and the line number it is executing and the error reporting should be as usual.

Example (output):

file1 line1: normal output (if any)

file1 line2: normal output (if any)

file2 line1: normal output (if any)

file2 line2: normal output (if any)

file1 line9: normal output (if any)

file1 line10: normal output (if any)

.......................................

Upvotes: 0

Views: 261

Answers (2)

Daniil Loban
Daniil Loban

Reputation: 4381

Use two internal modules of Python (linecache, sys) :

import linecache
import sys

def PrintException():
    exc_type, exc_obj, exc_info = sys.exc_info()
    f = exc_info.tb_frame
    lineno = exc_info.tb_lineno
    filename = f.f_code.co_filename
    linecache.checkcache(filename)
    line = linecache.getline(filename, lineno, f.f_globals)
    print ('{}, {} "{}" (Error: {})'.format(filename, lineno, line.strip(), exc_obj))

try:
    print (1/0) # place here code which you need check
except:
    PrintException()

Upvotes: 1

Jalaj
Jalaj

Reputation: 463

You just need to set up a log format of your choice that consists of lineno and pathname. Consider this file called test.py:

import logging
logging.basicConfig(
    format="%(pathname)s line%(lineno)s: %(message)s",
    level=logging.INFO
)
logging.info("test message")

And when you run this program,

$ python3 test.py
test.py line6: test message

Just paste the above snippet in any of your files. Make sure it is executed before any calls to any logging calls.

Here's a list of all parameters you can use in logging formats: logging.LogRecord

Upvotes: 1

Related Questions