3

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 Answers 3

5

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]: 
Sign up to request clarification or add additional context in comments.

Comments

1

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.

3 Comments

Or you can write your script in my_script.py, run ipython --pylab=tk and then type from my_script import *.
To be completely honest though, I'm still not entirely sure I understand what the question is. Do you think you could rephrase it?
sorry, i think the first answer solve my problem, but anyway, i updated the question...
0
%import numpy
%run my_python_file.py 

or I misunderstand your question.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.