Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send Python script to IPython or run Python script in IPython without importing numpy

I have a python file that contains scripts using numpy functions.

I thought IPython has numpy already loaded, so I didn't import numpy in the file, when I do:

%run my_python_file.py 

It fails due to the unknown functions from numpy.

So, my question is that:

Is there a way to run the scripts in a Python file with the modules already imported by IPython?

Thanks alot!

like image 611
shelper Avatar asked Dec 02 '25 09:12

shelper


1 Answers

If you're in the numpy -pylab interactive shell, use

run -i script.py

for what you're asking. It has the side effect of keeping around (or over-writing) any global variables in your python script. Basically, ipython acts as though you had typed the file in by hand.

Perhaps the most useful reason to do this is that you can also reference other variables created in the ipython session, e.g., changing them by hand between runs of the script.

For a trivial example, if script.py is

AA = np.array([[1,2],[3, myVar]])
print AA

then in ipython you could

In [1]: myVar = 7
In [2]: run -i script.py
[[1 2]
 [3 7]]
In [3]: myVar = 17
In [4]: run -i script.py
[[ 1  2]
 [ 3 17]]
In [5]: 
like image 171
daemacles Avatar answered Dec 03 '25 23:12

daemacles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!