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
]
  • Example notebook (using Python3)

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:

  • https://github.com/JuliaLang/pyjulia


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 Julia
j = Julia()
arr = j.run('[1:10]')
type(arr) # numpy.ndarray
  • http://blog.leahhanson.us/julia-calling-python-calling-julia.html

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 math
println(math.pi)
  • https://github.com/stevengj/PyCall.jl

Runing a script from your system shell

Use the shell mode syntax in a notebook cell:

;python my_script.py
  • http://julia.readthedocs.org/en/latest/manual/interacting-with-julia/?highlight=shell#shell-mode

Leave a Comment