Best way to run Julia code in an IPython notebook (or Python code in an IJulia notebook) Best way to run Julia code in an IPython notebook (or Python code in an IJulia notebook) python python

Best way to run Julia code in an IPython notebook (or Python code in an IJulia notebook)


Run Julia inside an IPython notebook


Hack

In order to run Julia snippets (or other language) inside an IPython notebook, I just append the string 'julia' to the default list in the _script_magics_default method from the ScriptMagics class in:

  • /usr/lib/python3.4/site-packages/IPython/core/magics/script.py or
  • /usr/lib/python2.7/site-packages/IPython/core/magics/script.py.

Example:

# like this:defaults = [    'sh',    'bash',    'perl',    'ruby',    'python',    'python2',    'python3',    'pypy',    'julia', # add your own magic]

IPython *Julia magic*

Julia Magic (Bi-directional)

To use %load_ext julia.magic, you would need to run the setup.py here:

Update (09/04/2014): the setup.py file has been moved to pyjulia.jl:

Which you get when Pkg.add("IJulia") clones the repo in your filesystem:

cd ~/.julia/v0.3/IJulia/python/sudo python2 setup.py install

Currently this only works for me in Python2. Python3 complains about:

ImportError: No module named 'core'

when I try to load the extention, but installs without complains.

After installing it you can also do this from inside Python2:

from julia import Juliaj = Julia()arr = j.run('[1:10]')type(arr) # numpy.ndarray

Runing a script from your system shell

Use the shell mode syntax in a notebook cell:

!julia my_script.jl



Run Python inside IJulia notebook


Using PyCall

It's not really running python code in the context you want, but you can also use Python libraries from within Julia:

using PyCall@pyimport mathprintln(math.pi)

Runing a script from your system shell

Use the shell mode syntax in a notebook cell:

;python my_script.py


Another option is to use Beaker. They have a tutorial notebook available that mixes R and Python; using Julia is just as easy.


If you want to run a whole notebook of only julia (or where you call other languages only from julia), then there is a cleaner solution. First, launch julia and do

Pkg.add("IJulia")

to get the IJulia package. Then you can

ipython notebook --profile julia

and your notebook will have julia as the native (default) language.

h/t to David Sanders and his excellent julia tutorials that are written in IPython notebooks; video here.