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

时间:2015-05-14 22:52:18

标签: julia jupyter ijulia-notebook

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

2 个答案:

答案 0 :(得分:2)

这是我写的:

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) 以运行代码,然后删除临时文件。这应该更加健壮(它通过了另一个失败的例子)。关于清洁/包装的相同评论适用。

{{1}}

答案 1 :(得分:0)

Julia软件包NBInclude.jl使这个过程变得容易:

using NBInclude
@nbinclude("myfile.ipynb")

运行整个笔记本,并返回最后评估的单元格的值。

相关问题