Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

julia object in python class init

I want to call a julia script out of my python code. No problem with pyjulia, but if I design it as a class there is a problem. I want to initialize julia and include a script in the init function. Below a example how I did is, I can't use self.jul in the funtion. it throws an error because self.jul has no function "myJulFuntion". And I'm sure it is inside the julia script, because if I move the stuff from init to callJulFunc and call jl.myJulFuntion(params) it works.

Any ideas?

The problem is,

import julia
julia.Julia()
from julia import Main as jl


class juliaStuff:
    def __init__(self):
        self.jul = jl
        jl.include("my-julia-script.jl")
     # or as alternative try
        self.jul.include("my-julia-script.jl")

    def callJulFunc(self, params ):
        return self.jul.myJulFuntion(params)

Edit: I adjustet my code. Now it crashes without an error at jl.include("my-julia-script.jl") or the alternative line.

@Hugo Trentesaux: In your code isn't a julia.Julia() init. without this it even doesn't work for me

My python version is 3.8.5 and julia is at 1.5.2

Edit 2: My problem is, that I'm using this in a Django Framework. Running a short example of this code is fine, but implementing it as a call from a views.py let's the django process crash after the include in the init. Just importing Main as jl and calling julia in a function is not a problem.

so in my views.py I added this:

# at the top of the file
import juliaStuff as ju

# in a function
jul= ju.juliaStuff()
jul_res = jul.callJulFunc(params)
like image 841
theother Avatar asked Jul 06 '26 23:07

theother


1 Answers

Try to move your julia import out of the class constructor and do not set self.jul as the output of jl.include:

# in script.jl
function hello()
 return "hello"
end
# in code.py
import julia
julia.Julia()
from julia import Main as jl

class juliaStuff:
    def __init__(self):
        self.jul = jl
        jl.include("script.jl")

    def callJulFunc(self):
        return self.jul.hello()

obj = juliaStuff()

print(obj.callJulFunc())

Calling the python code prints "hello" in the terminal.

like image 55
Hugo Trentesaux Avatar answered Jul 09 '26 16:07

Hugo Trentesaux



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!