Skip to content

Instantly share code, notes, and snippets.

@andreaferretti
Forked from apahl/nim_magic.py
Created June 14, 2018 14:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andreaferretti/1f3370927747da87c7a70319a78c2451 to your computer and use it in GitHub Desktop.
Save andreaferretti/1f3370927747da87c7a70319a78c2451 to your computer and use it in GitHub Desktop.
Nim cell magic for Jupyter and JLab Notebooks
"""
nim_magic.py
Jupyter cell magic for your favorite programming language.
Requirements: Nim (https://nim-lang.org), nimpy (`nimble install nimpy`, thanks to @yglukhov for this great library!)
Just put this file in some Python import dir
and then, in a Jupyter or JLab Notebook:
In [1]:
%load_ext nim_magic
In [2]:
%%nim mytest -d:release
proc greet(name: string): string {.exportpy.} =
return "Hello, " & name & "!"
In [3]:
mytest.greet("World")
"""
from IPython.core.magic import Magics, magics_class, cell_magic, needs_local_scope
from importlib import __import__
@magics_class
class NimMagics(Magics):
@cell_magic
def nim(self, options, code):
"""options must include the module name.
In addtion, further compile options, e.g. "-d:release" can be put here (separated by space)."""
import subprocess as sp
glbls = self.shell.user_ns
opt_list = options.split(" ", 1)
name = opt_list[0]
if name == "":
raise ValueError("module name is required. Try %%nim <mymodule> <compiler options>.")
if len(opt_list) > 1:
opt_str = opt_list[1]
else:
opt_str = ""
code = "import nimpy\n\n" + code
open("{}.nim".format(name), "w").write(code)
cmd = "nim c {} --app:lib --out:{}.so {}.nim".format(opt_str, name, name)
cp = sp.run(cmd, shell=True, check=False, encoding="utf8", stdout=sp.PIPE, stderr=sp.PIPE)
print(cp.stderr)
if cp.returncode == 0:
import_exec = "import {}".format(name)
exec(import_exec, glbls)
def load_ipython_extension(ipython):
"""
Any module file that define a function named `load_ipython_extension`
can be loaded via `%load_ext module.path` or be configured to be
autoloaded by IPython at startup time.
"""
# You can register the class itself without instantiating it. IPython will
# call the default constructor on it.
ipython.register_magics(NimMagics)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment