I've got a Python script which is running on a Linux server for hours, crunching some numbers for me. I'd like to check its progress, so I'd like to see what line is being executed right now. If that was a C or C++ program then I would just attach to the process with gdb -p <pid>
and examine the stacktrace with where
. Of course, I can do the same with the Python interpreter process, but I can't see the Python script's line in the stacktrace.
So, how can I find out which line of the Python script is being executed currently?
Function in the 'trace' module in Python library generates trace of program execution, and annotated statement coverage. It also has functions to list functions called during run by generating caller relationships.
In most PCs, Python interpreter is installed at /usr/local/bin/python3. 8. Instead of executing the instructions on CPU, bytecode instructions are executed on a Virtual Machine.
In python the code is executed line by line, but the whole execution start only after checking for syntax errors. The code only start to execute if all syntax errors are removed.
On all levels, if the code is called, it executes from top to bottom. On level 0 (the main level or the main function if you have one) the code is always executed.
You can add a signal handler to the Python script that sends this information to the terminal, or to a file, then hit ^C in the terminal to send the signal to the process.
import signal
def print_linenum(signum, frame):
print "Currently at line", frame.f_lineno
signal.signal(signal.SIGINT, print_linenum)
You could also use some other signal and use the kill
command to send the signal, if you need ^C to be able to interrupt the script, or set a signal.alarm()
to print the information periodically, e.g. once a second.
You could print out other things from the stack frame if you like; there's a lot there. See the attributes of frame
objects in this table.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With