Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check which line of a Python script is being executed?

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?

like image 326
piokuc Avatar asked Jul 03 '13 22:07

piokuc


People also ask

How do you trace a Python program execution?

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.

Where is Python code executed?

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.

How Python code is executed line by line?

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.

Is Python executed from top to bottom?

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.


1 Answers

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.

like image 139
kindall Avatar answered Oct 24 '22 02:10

kindall