Single line or short script to run code inside a Jupyter laptop?

I like to develop scripts by running them in parts on a Jupyter laptop (nee iJulia). However, sometimes I need to check things on a remote system and you only need to make a copy of the code in the form of a .jl file. Has anyone already written a single-line or short script that runs code in a .ipynb laptop? If not, at some point I will get to it and send the code here.

+4
source share
1 answer

Here is what I wrote:

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) for c in cells]
extract_code(j::Dict) = extract_code(get_code_cells(j))
eval_code(j::Dict) = map(eval, extract_code(j))


# get filename, then parse to json, then run all code
const fn = ARGS[1]
eval_code(JSON.parsefile(fn))

This seems to work for many laptops, but not for everyone. In particular, he could not start the laptop, where I had

using PyCall
@pyimport seaborn as sns

eval , @pyimport, ( PyCall).

, , .


- ...

ipython nbconvert, , include , . ( , ). / .

const fn = abspath(ARGS[1])
dir = dirname(fn)

# shell out to nbconvert to get a string with code
src = readall(`ipython nbconvert --to script --stdout $fn`)

# Generate random filenamein this directory, write code string to it
script_fn = joinpath(dir, string(randstring(30), ".jl"))
open(script_fn, "w") do f
    write(f, src)
end

# now try to run the file we just write. We do this so we can make sure
# to get to the call `rm(script_fn)` below.
try
    include(script_fn)
catch
    warn("Failed executing script from file")
end

# clean up by deleting the temporary file we created
rm(script_fn)
+2

All Articles