在我的iPython笔记本和iJulia中,是否可以调用其他文件(的函数)?到目前为止,我一直在一个大的.ipynb文件中使用所有方法,但它变得太大了。是否有一种方法将一些函数传输到其他文件中,以便从那里调用它们?
您可以在一个.jl
文件中定义函数,然后在笔记本中使用include
命令将其引入。
如果您有一个名为test.jl
的文件,其中包含以下内容:
function helloworld()
println("Hello, World!")
end
您可以从笔记本中调用它,然后它将被评估。然后您可以像平常一样使用文件中定义的函数:
In [1]: include("test.jl")
Out[1]: helloworld (generic function with 1 method)
In [2]: helloworld()
Hello, world!
编辑:
从另一个ipynb
文件运行代码要困难得多,因为代码嵌入到笔记本的json中。如果你真的想要这个功能,应该这样实现:
using PyCall
function execute_notebook(nbfile)
@pyimport IPython.nbformat.current as ipyt
open(nbfile) do f
nbstring = readall(f)
nb = ipyt.reads(nbstring, "json")
for cell in nb["worksheets"][1]["cells"]
eval(parse(cell["input"]))
end
end
end
目前会抛出一个错误,但它似乎仍然可以工作。如果您有一个名为test.ipynb
的文件,并在其中定义了相同的helloworld()
函数,则可以从另一个笔记本中调用它:
execute_notebook("test.ipynb")
helloworld()
我仍然建议将你从其他地方调用的代码放在一个 .jl
文件中,而不是一个 .ipynb
文件中。这样更简单,可能也更健壮。
-
has no method matching -(::ASCIIString, ::ASCIIString) while loading C:****\temp.ipynb, in expression starting on line 1 while loading In[43], in expression starting on line 1 in colon at range.jl:75 in include at boot.jl:245 in include_from_node1 at loading.jl:128 - Guido