gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:41:41 25 4
gpt4 key购买 nike

我喜欢通过在 Jupyter (nee iJulia) notebook 中逐步运行脚本来开发脚本。但是,有时我需要在远程系统上进行测试,并且需要将代码复制为 .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 导出的)。

如果您有兴趣,我们绝对可以清理它,添加更多参数并将其打包到适当的命令行实用程序中。

编辑

现在是完全不同的东西......

此版本弹 shell 到 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 - 在 Jupyter 笔记本中运行代码的单行脚本或短脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30248783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com