Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method to peek at a Python program running right now

Is it possible to find any information about what a Python program running right now is doing without interrupting it?

Also, if it isn't possible, is there anyway to crash a running Python program so that I can at least get a stacktrace (using PyDev on Ubuntu)?

I know I should have used logs or run it in debug mode or inserted a statement to run the debugger...

Related questions

  • Getting stack trace from a running Python program - Very similar, but more general, this question was intended to be about debugging a Python program that is running right now.
like image 498
Casebash Avatar asked Oct 28 '09 13:10

Casebash


People also ask

How do I check if a Python process is running?

To check if process is running or not, let's iterate over all the running process using psutil. process_iter() and match the process name i.e. import psutil def checkIfProcessRunning(processName): ''' Check if there is any running process that contains the given name processName.

How do you check Python script execution time?

time() : Measure the the total time elapsed to execute the code in seconds. timeit. timeit() : Simple way to time a small piece of Python code. %timeit and %%timeit : command to get the execution time of a single line of code and multiple lines of code.

How do you get a stack trace for each thread in a running Python script?

Inspect running process with pyrasite Find the process ID for the stuck Python process and run pyrasite-shell with it. You should now see a Python REPL. Run the following in the REPL to see stack traces for all threads.


2 Answers

If you place

import code
code.interact(local=locals())

at any point in your script, python will instantiate a python shell at exactly that point that has access to everything in the state of the script at that point. ^D exits the shell and resumes execution past that point.

You can even modify the state at that point from the shell, call functions, etc.

like image 168
ʞɔıu Avatar answered Sep 19 '22 20:09

ʞɔıu


If you have a running Python, which wasn't built with any sort of trace or logging mechanism, and you want to see what it's doing internally, then two options are:

  • On a Solaris or Mac, if you are using the system-provided Python then use dtrace

  • use gdb to attach to a running Python process,

like image 21
Andrew Dalke Avatar answered Sep 21 '22 20:09

Andrew Dalke