Julia 在Jupyter笔记本中运行代码的一行或短脚本?

Julia 在Jupyter笔记本中运行代码的一行或短脚本?,julia,jupyter,ijulia-notebook,Julia,Jupyter,Ijulia Notebook,我喜欢通过在Jupyter(nee iJulia)笔记本上零碎地运行脚本来开发脚本。但是,有时我需要在远程系统上测试,并且需要将代码作为.jl文件进行复制。是否有人已经在.ipynb笔记本中编写了一行或短脚本来运行代码?如果没有,我会在某个时候找到它并在这里发布代码 以下是我写的: using JSON get_code_cells(j::Dict) = filter(x->x["cell_type"] == "code", j["cells"]) function parse_cod

我喜欢通过在Jupyter(nee iJulia)笔记本上零碎地运行脚本来开发脚本。但是,有时我需要在远程系统上测试,并且需要将代码作为.jl文件进行复制。是否有人已经在.ipynb笔记本中编写了一行或短脚本来运行代码?如果没有,我会在某个时候找到它并在这里发布代码

以下是我写的:

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))
它似乎适用于许多笔记本,但不是所有的笔记本。具体地说,它没能在我的笔记本上运行

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)
Julia软件包使这变得简单:

using NBInclude
@nbinclude("myfile.ipynb")

运行整个笔记本并返回最后一个计算单元的值。

从笔记本中,是否
文件->下载为->Julia(txt)
足够?这就是我一直在做的,尽管我想用某种方法运行代码,而不必将其另存为单独的文件,比如“Julia parser.jl notebook.ipnb”