IJulia Files for Notebooks (iPython)

In my iPython notebook with iJulia, can (functions) be called from other files? So far I have worked in one big .ipynb file using all methods, but it gets too big. Is there a way to transfer some of the functions to other files to call them from there?

+3


source to share


1 answer


You can define your functions in a file .jl

and then include

in a notebook.

If you have a file named test.jl

with content:

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

      

you can call it from laptop and it will be appreciated. Then you can use the function defined in the file as usual:

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

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

      



EDIT: Running the code from another file is ipynb

much more difficult because the code is being put into the json of the notebook. If you really want this feature to 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 is currently throwing an error, but it still works. If you have one test.ipynb

with the same function helloworld()

that you could call from another laptop with:

execute_notebook("test.ipynb")
helloworld()

      

I still recommend storing the code you intend to call from elsewhere in a file .jl

rather than a file .ipynb

. It's simpler and probably more reliable.

+7


source







All Articles