Exchange data between interactive_mode and script_mode?

Viewed 206

Suppose to run a block of code in script_mode and produce such data:

my_data = [1, 2, 3, 4] #please note this is output after running not data in script

Now I switch to work in console for debugging the code. I need to use the data produced just now, while cannot copy directly for avoiding the effect of gibberish. My solution is to pickle first in the script_mode and unpickle it in interactive_mode:

Codes with 5 commands:

Script Mode

import pickle

with open('my_data','wb') as file:
        pickle.dump(my_data, file)

Interactive_mode:

import os, pickle
# change to the working directory
os.chdir('~\..\')
with open('my_data', 'rb') as file:
         my_data = pickle.load(file)
# my_data is finally loaded in console
# then manipulate it on the console.

How to do it in less steps?

3 Answers

You can run the file with the -i option, like python -i your_file_name.py.

This will run your file first, then open an interactive shell with all of the variables present and ready for use.

If, in your /path/to/your/project directory, you have the script your_script.py like this:

my_data = [1, 2, 3, 4]

If you want to debug your script in a Python 2 interactive shell, you can do:

$ python
>>> execfile('/path/to/your/project/your_script.py')

Or, with the Python 2+3 way:

>>> exec(open('/path/to/your/project/your_script.py').read(), globals())

The built-in function exec() supports dynamic execution of Python code. The built-in function globals() returns the current global dictionary. That way you can access to your data:

>>> my_data
[1, 2, 3, 4]

Personally, I would use IPython, just:

pip install IPython

Then anywhere you want to drop into a console, simply

import IPython

at the top of the file and use:

IPython.embed()

where you'd like to drop in.

You can type "whos" once you're in for a list of variables alongside their type and values. It's pretty useful, but yeah, this should work for you. IPython is a solid python shell.

You can also use ipdb if you're more used to the standard pdb. It's really good too.

Related