18

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!

4

2 に答える 2

26

IPython の magic run コマンドで -i オプションを使用してみてください。現在のインタラクティブな名前空間を使用してスクリプトを実行します。

ロード.py:

a = 5

tst.py:

print a

IPython から取得します。

In [1]: from load import *

In [2]: run -i tst
5
于 2012-05-16T16:36:46.827 に答える
2

これを行うための簡単でスマートな方法はありません。1 つの方法はmain、テスト関数に関数を用意しglobals、環境から を渡してglobals、呼び出し元で を更新することです。例えば:

tst.py

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

そして、iPythonで:

In [1]: a = 5

In [2]: import tst

In [3]: tst.main(globals())
5
于 2012-05-16T16:34:39.100 に答える