2

I write a Python 2.5 Command Line program on CentOS 5.5 and it has been running for 1 day and is still running. Now I want to end this program but get the value of a global variable.

I have done some Google. It seems the only way to get the value of a global variable is to attach the Python program to a GDB.

Suppose the global variable is a List, and its name is resultlist. How can I get its value?

2 Answers 2

6

This is possible to do, but is extremely tricky, and a single wrong move will cause the program to crash (or be lost in an indeterminate state).

You can use the C function PyEval_GetGlobals() to return the dictionary of globals (as it would if you called globals() in python), and then use PyObject_Print() to print that object to a file (the easiest being whatever stdout is connected to).

You'll want to run GDB and attach it to the instance of python. Then set a breakpoint on a function you know will be called (if your program is printing output, then PyObject_Print() will work; otherwise this page has some functions that probably get called a lot.), then when the program hits the breakpoint, you'll want to disable it, and print the globals.

For example, if my Python program has a PID of 15847:

(gdb) attach 15847
Attaching to process 15847.
Reading symbols for shared libraries . done
Reading symbols for shared libraries ............. done
0x00007fff870b5e52 in select$DARWIN_EXTSN ()
(gdb) break PyObject_Print
Breakpoint 1 at 0x10003d8f4
(gdb) c
Continuing.

The next time your program goes to print something:

Breakpoint 1, 0x000000010003d8f4 in PyObject_Print ()
(gdb) disable
(gdb) call (int)PyObject_Print((void*)PyEval_GetGlobals())
$1 = 0
(gdb) c
Continuing.

Then, in the output of your program, you'll see the global dictionary.

Sign up to request clarification or add additional context in comments.

Comments

0

I'm afraid names won't help you much. Since you didn't build in some printing mechanism and your process is already running you're pretty much screwed.

If you have an idea what the values might be your best bet would be using a process memory scanner and start messing around. Though I estimate your chances of success very low, I'm sorry.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.