一线还是短脚本在Jupyter笔记本中运行代码?

我喜欢通过在Jupyter(nee iJulia)笔记本中逐行运行脚本来开发脚本。但是,有时我需要在远程系统上进行测试,并且需要将代码复制为.jl文件。是否有人已经编写了在.ipynb笔记本中运行代码的单行脚本或简短脚本?如果没有,我将在某个时候进行讨论并在此处发布代码。

spencerlyon2

这是我写的:

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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

bash脚本在virtualenv中运行jupyter笔记本

jupyter笔记本中的VS代码?

如何隐藏代码并重新运行Jupyter笔记本中的所有单元格?

如何在Jupyter笔记本中运行Python异步代码?

从另一个笔记本运行Jupyter笔记本

Jupyter可以在Python笔记本中运行单独的R笔记本吗?

如何从Jupyter笔记本中获取原始代码?

如何在Jupyter笔记本中包装代码/文本

在Jupyter笔记本中隐藏代码(报告模式)

是否可以在Jupyter笔记本中运行pypy内核?

在pytest中运行Jupyter笔记本测试。OSError

在不同环境中运行内核的jupyter笔记本

在virtualenv中运行“ jupyter笔记本”并返回AttributeError

% 运行另一个笔记本时,Jupyter 中的编码错误

如何显示Jupyter笔记本的版本并在Jupyter笔记本中运行单元格?我收到一个错误:翻译错误

仅Jupyter笔记本显示代码

无法运行Jupyter笔记本

从另一个笔记本运行Jupyter笔记本,同时更改正在运行的笔记本的输出

在IPython笔记本(或IJulia笔记本中的Python代码)中运行Julia代码的最佳方法

jupyter笔记本中的内存错误

jupyter笔记本中的内存限制

在jupyter笔记本python中密谋

Jupyter笔记本中的Imagegrid

不同笔记本中的 Jupyter 类?

jupyter笔记本中的打字稿

无法在Jupyter笔记本中绘图

在Firefox中冻结的jupyter笔记本

如何在每个jupyter笔记本内核之前运行Python代码

我可以在GPU上运行包含季节性代码的jupyter笔记本吗?