Exchange between interactive_mode and script_mode?

Suppose you run a code block in script_mode and produce the following data:

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

Now I switch to console work to debug the code. I need to use the data created now, and not copy directly to avoid the gibberish effect. My solution is to sort first in script_mode and sprinkle 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 fewer steps?

+4
source share
3 answers

You can run a file with a parameter -i, for example python -i your_file_name.py.

, .

+2

/path/to/your/project script your_script.py, :

my_data = [1, 2, 3, 4]

script Python 2, :

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

, Python 2 + 3:

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

exec() Python. globals() . :

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

IPython, :

pip install IPython

,

import IPython

:

IPython.embed()

.

"whos", . , , . IPython - python.

You can also use ipdb if you are more used to standard pdb. This is really good.

+1
source

Source: https://habr.com/ru/post/1683400/


All Articles