I'm trying to run a file inside the ipython interpreter.
The documentation makes this sound as simple as ipython file.py
in the shell or %run file.py
inside the interpreter itself. However, I want to read a file that contains commands to the ipython "system shell". Here's an example:
files= !ls
print files
for this type of commands, invoking the interpreter as mentioned above results in SyntaxError, as if it was executed by /usr/bin/python
.
Is it possible to run a file from the system shell as if it were executing inside the ipython shell interpreter?
You can use run command in the input prompt to run a Python script. The run command is actually line magic command and should actually be written as %run. However, the %automagic mode is always on by default, so you can omit this.
A text file can be loaded in a notebook cell with the magic command %load . the content of filename.py will be loaded in the next cell. You can edit and execute it as usual.
Start by launching the IPython interpreter by typing ipython on the command-line; alternatively, if you've installed a distribution like Anaconda or EPD, there may be a launcher specific to your system (we'll discuss this more fully in Help and Documentation in IPython).
It looks like you can do this if you name your file with an .ipy extension.
sam@blackbird-debian:~
$ cat tmp.ipy
me = !whoami
print me
sam@blackbird-debian:~
$ ipython tmp.ipy
['sam']
I assume you want to do this from an already running IPython session. There is probably something much simpler, but all I could think of right now is:
get_ipython().shell.run_cell(open('path/to/commands').read())
Another crazy idea - start IPython as EDITOR=cat ipython
. Now you can load commands from a file with:
%edit -r path/to/commands
There should probably be a real magic for your use case, though.
Or you could do the same thing non-interactively (add -i
to drop into interactive mode):
ipython -c 'get_ipython().shell.run_cell(open("path/to/commands").read())'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With