O
O
Onotolius2021-08-25 14:24:53
Python
Onotolius, 2021-08-25 14:24:53

How to find out the line in which the python code was executed?

Hello.

Here is a sample code: in this case, the statement "print('hehe')" is in the 2nd line, how to display what is the second line? In php, for example, there is a "magic constant" __LINE__ for this. For example: In python, it should also be like that, but how?

print('hehe')


echo 'hehe ' . __LINE__; // выведет "hehe 2"

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Karbivnichy, 2021-08-25
@Login8

1) You can include the Logging package ( Logging in Python )
2) You can use something like this:

def debug(msg):
     import sys
     frame = sys._getframe(1)

     name = frame.f_code.co_name
     line_number = frame.f_lineno
     filename = frame.f_code.co_filename

     return 'File "%s", line %d, in %s: %s' % (filename, line_number, name, msg)

print(debug('hehe'))

At the output we get:
File "/home/sergey/Рабочий стол/Projects/l.py", line 12, in <module>: hehe

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question