Skip to content
Advertisement

python: is it possible to attach a console into a running process

I just want to see the state of the process, is it possible to attach a console into the process, so I can invoke functions inside the process and see some of the global variables.

It’s better the process is running without being affected(of course performance can down a little bit)

Advertisement

Answer

If you have access to the program’s source-code, you can add this functionality relatively easily.

See Recipe 576515: Debugging a running python process by interrupting and providing an interactive prompt (Python)

To quote:

This provides code to allow any python program which uses it to be interrupted at the current point, and communicated with via a normal python interactive console. This allows the locals, globals and associated program state to be investigated, as well as calling arbitrary functions and classes.

To use, a process should import the module, and call listen() at any point during startup. To interrupt this process, the script can be run directly, giving the process Id of the process to debug as the parameter.


Another implementation of roughly the same concept is provided by rconsole. From the documentation:

rconsole is a remote Python console with auto completion, which can be used to inspect and modify the namespace of a running script.

To invoke in a script do:

from rfoo.utils import rconsole
rconsole.spawn_server()

To attach from a shell do:

$ rconsole

Security note: The rconsole listener started with spawn_server() will accept any local connection and may therefore be insecure to use in shared hosting or similar environments!

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement