Reputation: 23322
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?
Upvotes: 7
Views: 6382
Reputation: 5983
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']
Upvotes: 5
Reputation: 4097
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())'
Upvotes: 4
Reputation: 3616
Depending on what exactly you want to do, it may be sufficient to run
ipython < file
from bash. That is, just redirect standard input to ipython from your file, so that ipython thinks the commands it's getting are coming from your keyboard.
Upvotes: 0