julia lang - One-liner or short script to run the code inside a Jupyter notebook? -
i develop scripts running them piecemeal in jupyter (nee ijulia) notebook. however, need test things on remote system , need make copy of code .jl file. has written one-liner or short script runs code in .ipynb notebook? if not, i'll @ point , post code here.
here's have written up:
using json get_code_cells(j::dict) = filter(x->x["cell_type"] == "code", j["cells"]) function parse_code_cell(c::dict) buf = iobuffer() write(buf, "begin\n") map(x->write(buf, x), c["source"]) write(buf, "\nend") src = bytestring(buf) parse(src) end extract_code(cells::vector) = expr[parse_code_cell(c) c in cells] extract_code(j::dict) = extract_code(get_code_cells(j)) eval_code(j::dict) = map(eval, extract_code(j)) # filename, parse json, run code const fn = args[1] eval_code(json.parsefile(fn))
it seems work many notebooks, not everything. specifically, failed run notebook had
using pycall @pyimport seaborn sns
when eval
hit chunk of code complained @pyimport
not being defined (even though exported pycall
).
if interested, clean up, add more arguments , package proper command line utility.
edit
now different...
this version shells out ipython nbconvert
, writes temporary file, calls include
on temporary file run code, deletes temp file. should more robust (it passed examples other 1 failed at). same comments cleaning/packaging apply.
const fn = abspath(args[1]) dir = dirname(fn) # shell out nbconvert string code src = readall(`ipython nbconvert --to script --stdout $fn`) # generate random filenamein directory, write code string script_fn = joinpath(dir, string(randstring(30), ".jl")) open(script_fn, "w") f write(f, src) end # try run file write. can make sure # call `rm(script_fn)` below. try include(script_fn) catch warn("failed executing script file") end # clean deleting temporary file created rm(script_fn)
Comments
Post a Comment