Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iJulia notebook (iPython) files

In my iPython notebook with iJulia, is it possible to call (functions from) other files? Until now, I worked in one big .ipynb file using all methods, but it is getting too large. Is there a way to transport some functions to other files, in order to call them from there?

like image 935
Guido Avatar asked Aug 10 '26 13:08

Guido


1 Answers

You can define your functions in a .jl file and then include it in the notebook.

If you have a file called test.jl with the content:

function helloworld()
    println("Hello, World!")
end

you can then call it from the notebook and it will be evaluated. You can then use function defined in the file as normal:

In [1]: include("test.jl")    
Out[1]: helloworld (generic function with 1 method)

In [2]: helloworld()
Hello, world!

EDIT: To run code from another ipynb file is much trickier because the code is emedded into the json of the notebook. If you really want to this function should work:

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

It currently throws an error but it still appears to work. If you have a test.ipynb with the same helloworld() function defined you could then call it from another notebook with:

execute_notebook("test.ipynb")
helloworld()

I'd still recommend keeping code you are going to call from other places in a .jl file rather than in a .ipynb file. It is simpler and probably more robust.

like image 136
Mr Alpha Avatar answered Aug 13 '26 18:08

Mr Alpha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!