Calling a Python script with PyCall

I have some old Python set of scripts, and would like to call a function (just one function) from there into Julia. How can I do it? Win10, conda.

using PyCall
pushfirst!(PyVector(pyimport("sys")."path"), "")
mys = pyimport("py_test.py")

results in

The Python package py_test.py could not be found by pyimport. Usually this means
that you did not install py_test.py in the Python version being used by PyCall.

PyCall is currently configured to use the Python version at:

C:\Users\eben60\AppData\Local\Continuum\miniconda3\python.exe

and you should use whatever mechanism you usually use (apt-get, pip, conda,
etcetera) to install the Python package containing the py_test.py module.

Is installing my Python script the only way to get it callable from Julia? If so, what would be the simplest way to do it?

OK, I have found a workaround: Using pyjulia to call Julia function from Python and passing the Julia function the reference to my Python object, like this:

py_test.py :

class pyob():
    def __init__(self, x):
        self.a = x

    def amulx(self, x):
        return self.a*x

jul_test.jl :

function jlf(pyfun)
    for i in 1:2
        println(pyfun(i))
    end
end

py_wrap.py :

from py_test import pyob
from julia import Main as JL
JL.include("jul_test.jl")

p = pyob(1.0)
JL.jlf(p.amulx)
1 Like

I think you meant to write pyimport("py_test").

1 Like

thank you! Now the import doesn’t throw an error.

But now the next question: How do I call an object from the script? Calling p = mys.py_test.pyob(2) or p = mys.pyob(2) or p = pyob(2) results in an error

ERROR: LoadError: KeyError: key "pyob" not found

After I restarted Julia REPL, it now works OK:

p = mys.pyob(2)
@show p.amulx(3.0)
> p.amulx(3.0) = 6.0

In case the calling Julia script and the called Python script are in the same directory (e.g. ./src ), to properly include the directory:

using PyCall
scriptdir = @__DIR__
pushfirst!(PyVector(pyimport("sys")."path"), scriptdir)
mytest = pyimport("test_py")
3 Likes