0

I understand there are ways of writing a Python script so that upon execution from the terminal you will be entered into the interpreter with the ending state of the variables preserved.

Is it possible to cut off a python script mid-execution and go into the interpreter with the state at that point in the script preserved? For example, I have a large loop, which at every iteration enters a new key,value pair into a dictionary. At the end of the loop the dictionary is written out to a file. Upon running the script now for a couple hours, I realize that its not worth letting it finish, but I would still like to see the dictionary up to this point.

The script is running in my terminal right now - is there any to jump to the interpreter from here and see the current state of the dictionary?

EDIT: entering into interpreter AFTER running script (with state preserved)

python -i script.py
OregEmber
  • 45
  • 6

3 Answers3

0

You cannot just 'drop it' to interactive console, if you are already running it

However, you can try to attach to running process with gdb, see https://wiki.python.org/moin/DebuggingWithGdb:

$ gdb python <pid of running process>

And then try to debug it as you would do with C process.

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

Community
  • 1
  • 1
m.wasowski
  • 6,329
  • 1
  • 23
  • 30
0

Here example of kinda dirty workaround, using try except and raw_input (for python 2.7). This won't get you into interpreter, but you can pause script with this using ctrl+c and print needed variable to know its state.

import time

t = 0

while 1:
    try:
        print time.time()
        time.sleep(5)
        t += 1
    except KeyboardInterrupt:
        print '\nt = {}'.format(t)
        # time.sleep(5)
        raw_input("Script paused! Enter anything to continue or press Ctrl+C to stop execution.")

You can even place in except block call to pdb:

import pdb
pdb.set_trace()

to get into debugger, in which you can use python console.

pavel_form
  • 1,760
  • 13
  • 14
-1

No, you can't. If you want to restart your script from a concrete status, you must preserve this state and load it when the execution of your script is restarted. In your case, use a temporal file with the values calculated and other to control the flow. And don't forget to delete the file on success.

Miguel Prz
  • 13,718
  • 29
  • 42
  • I'm sorry I'm still a little confused. You mean to say I can at least pause the script and continue it running later? – OregEmber Aug 06 '14 at 11:36