Execute file in ipython interpreter

I am 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 the file containing the commands for the ipython "system shell". Here is an example:

 files= !ls print files 

for this type of command, invoking the interpreter, as mentioned above, results in a SyntaxError as if it were being executed using /usr/bin/python .

Is it possible to run a file from the system shell as if it were running inside the ipython shell interpreter?

+6
source share
3 answers

It looks like you can do this if you name your file the extension .ipy.

 sam@blackbird-debian :~ $ cat tmp.ipy me = !whoami print me sam@blackbird-debian :~ $ ipython tmp.ipy ['sam'] 
+5
source

I assume you want to do this from an already running IPython session. There is probably something a lot , but all that I could think of now:

 get_ipython().shell.run_cell(open('path/to/commands').read()) 

Another crazy idea is to run IPython as EDITOR=cat ipython . Now you can load commands from a file with:

 %edit -r path/to/commands 

Probably for your use case, there probably should be real magic.


Or you can do the same non-interactively (add -i to interactive mode):

 ipython -c 'get_ipython().shell.run_cell(open("path/to/commands").read())' 
+4
source

Depending on what exactly you want to do, it may be enough to run

 ipython < file 

from bash. That is, just redirect the standard input to ipython from your file, so that ipython thinks that the commands it receives come from your keyboard.

0
source

All Articles