3
votes

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!

3

3 Answers

5
votes

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]: 
1
votes

Well, if I understand you correctly, assuming you're running linux, you could do something like this:

#!/usr/bin/ipython --pylab=tk
print(numpy.sin(0.5))

The line with #! indicates to the script what program (and options) to use to run it and the the numpy line is just an example to show you that it works. You may need to replace tk with Qt4 or something similar.

Then you will need to run the command chmod +x (assuming you're on a unix machine) on this file to make it executable and run it.

The real question is why not just import numpy in your script? If you explain that perhaps we can help you find the best solution to your problem.

0
votes
%import numpy
%run my_python_file.py 

or I misunderstand your question.