简体   繁体   中英

Julia Calling Python Function

I've been trying to call python functions from Julia using this code:

using PyCall
unshift!(PyVector(pyimport("sys")["path"]), "")
@pyimport testing
print(testing.add())

testing is in the same path.

the testing python file:

def add():
    return 5 + 5

I am getting this error from Julia though:

LoadError: PyError (ccall(@pysym(:PyImport_ImportModule), PyPtr, (Cstring,), 
name)) <class 'ImportError'> ImportError("No module named 'testing'",)

while loading C:\Users\Benjamin\AppData\Local\JuliaPro-0.6.0.1\test.jl, in expression starting on line 410
pyerr_check at exception.jl:56 [inlined]
pyerr_check at exception.jl:61 [inlined]
macro expansion at exception.jl:81 [inlined]
pyimport(::String) at PyCall.jl:370
include_string(::String, ::String) at loading.jl:515
include_string(::Module, ::String, ::String) at Compat.jl:577
(::Atom.##55#58{String,String})() at eval.jl:73
withpath(::Atom.##55#58{String,String}, ::String) at utils.jl:30
withpath(::Function, ::String) at eval.jl:38
macro expansion at eval.jl:71 [inlined]
(::Atom.##54#57{Dict{String,Any}})() at task.jl:80

How can I fix this?

Also how can I do this: (Julia):

using PyCall
unshift!(PyVector(pyimport("sys")["path"]), "")
@pyimport testing
print(testing.add(5, 5))

(Python):

def add(a, b):
    return a + b

This works for me as you expect if I rename your testing.py file to something different, like mytests.py :

julia> using PyCall

julia> unshift!(PyVector(pyimport("sys")["path"]), "")
PyObject ['', … ]

julia> @pyimport mytests

julia> mytests.add(5,5)
10

I have a testing package in my site-packages folder, which may be causing the trouble:

julia> @pyimport testing

julia> testing.__path__
1-element Array{String,1}:
 "/.../lib/python2.7/site-packages/testing"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM