Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute file in ipython interpreter

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?

like image 458
loopbackbee Avatar asked Nov 13 '12 23:11

loopbackbee


People also ask

How do I run an IPython file?

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.

How do I load files into IPython?

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.

How do I run IPython interpreter?

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).


2 Answers

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']
like image 156
Sam Mussmann Avatar answered Sep 30 '22 14:09

Sam Mussmann


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())'
like image 45
gvalkov Avatar answered Sep 30 '22 14:09

gvalkov