Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing variables from IPython interactive namespace in a script

Tags:

python

ipython

Is there an easy way to access variables in the IPython interactive namespace. While implementing a project that has a slow load command, I would like to run a script to load the data into the interactive work space, then call a second script that uses the data, like is possible with MATLAB.

In this simple case, what I want to do is

In [20]: a=5

In [21]: run tst

where tst.py is just

print a

The idea is that I want to run the loading script once, then just work on tst.py.

Thanks!

like image 984
user1398968 Avatar asked May 16 '12 16:05

user1398968


2 Answers

Try using the -i option on IPython's magic run command; it makes the script run using the current interactive namespace, e.g. with

load.py:

a = 5

tst.py:

print a

From IPython I get;

In [1]: from load import *

In [2]: run -i tst
5
like image 96
jeremiahbuddha Avatar answered Sep 22 '22 16:09

jeremiahbuddha


There is no easy or smart way to do this. One way would be to have a main function in your test function and then pass in the globals from your environment to update the globals in the caller. For example:

tst.py

def main(borrowed_globals):
    globals().update(borrowed_globals)
    print a

And then in iPython:

In [1]: a = 5

In [2]: import tst

In [3]: tst.main(globals())
5
like image 40
bossylobster Avatar answered Sep 20 '22 16:09

bossylobster