How to load and call functions defined in a standalone Python script?

Can PyCall be used to load definitions from a small Python script into Julia? For example, how can I call foo() defined in the Python script below in Julia?

a = 1
b = 2
def foo():
    print("Hello world!")
    return a + b

Just do what you would have done in python

julia> using PyCall

julia> push!(pyimport("sys")["path"], pwd());

julia> pyimport("a")[:foo]()
Hello world!
3
1 Like

Thank you @yuyichao, I will give the solution a try. :slight_smile:

“path” is the path to the python file, right?

No. As I said, do what you would’ve done in python (add an path to sys.path).

confused still…

pyimport("sys")["path"] was accessing sys.path in python (the syntax might have changed). I’m not really sure what(else) you are asking about…

Hi yuyichao,

Thank you for your solution. It’s just what I want to find. But 2 years later the syntax may have changed. I tried your suggested code in JuliaPro 1.0.4 win64 and met several errors.
According to Julia’s suggestion, I changed
push!(pyimport(“sys”)[“path”], pwd())
to
pushfirst!(PyVector(pyimport(“sys”).“path”), “”)
It worked.
Bit there’s a warning for
pyimport(“a”):foo
Warning: @pyimport foo is deprecated in favor of foo = pyimport("foo")
I changed it to
foo = pyimport(“foo”)
or
foo = pyimport(“foo.py”)
Bot of them did not work.
I searched on internet and found no answers.
Do you know the updated syntax to call a Python script .py file?
I also want to call one of the functions in that file. Something like
y = foo.fun_01(5)
println(“y=”, y)

Your reply will be appreciated.

Thanks,

Larry