Running Scripts from IPython



In [1]:
import sys

Basic usage


In [2]:
%%script python2
import sys
print 'hello from Python %s' % sys.version
In [3]:
%%script python3
import sys
[GCC 4.2.1 (Apple Inc. build 5577)]


These are all equivalent to %%script <name>

In [4]:
puts "Hello from Ruby #{RUBY_VERSION}"
Hello from Ruby 2.0.0
In [5]:
echo "hello from $BASH"
hello from /usr/local/bin/bash

Capturing output


In [6]:
echo "hi, stdout"
echo "hello, stderr" >&2
hi, stdout
hello, stderr
In [7]:
%%bash --out output --err error
echo "hi, stdout"
echo "hello, stderr" >&2
In [8]:
hello, stderr

hi, stdout

Background Scripts



In [9]:
%%ruby --bg --out ruby_lines
for n in 1...10
    sleep 1
    puts "line #{n}"
Starting job # 0 in a separate thread.


In [10]:
<open file '<fdopen>', mode 'rb' at 0x10a4be660>
In [11]:
line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8
line 9

Arguments to subcommand

You can pass arguments the subcommand as well, such as this example instructing Python to use integer division from Python 3:

In [12]:
%%script python2 -Qnew
print 1/3

You can really specify any program for %%script, for instance here is a 'program' that echos the lines of stdin, with delays between each line.

In [13]:
%%script --bg --out bashout bash -c "while read line; do echo $line; sleep 1; done"
line 1
line 2
line 3
line 4
line 5
Starting job # 2 in a separate thread.

Remember, since the output of a background script is just the stdout pipe, you can read it as lines become available:

In [14]:
import time
tic = time.time()
line = True
while True:
    line = bashout.readline()
    if not line:
    sys.stdout.write("%.1fs: %s" %(time.time()-tic, line))
0.0s: line 1
1.0s: line 2
2.0s: line 3
3.0s: line 4
4.0s: line 5

Configuring the default ScriptMagics

The list of aliased script magics is configurable.

The default is to pick from a few common interpreters, and use them if found, but you can specify your own in

c.ScriptMagics.scripts = ['R', 'pypy', 'myprogram']

And if any of these programs do not apear on your default PATH, then you would also need to specify their location with:

c.ScriptMagics.script_paths = {'myprogram': '/opt/path/to/myprogram'}