Skip to content

v0.4 support #38

Closed
JuliaPy/PyCall.jl
#219

Description

@jpfairbanks

I was trying to use this in an ipython notebook to support julia v0.4 but ran into this exception.
JuliaError: error starting up the Julia process. The problem is in core.py:237
in 0.4 Sys.dlpath does not exist it was moved to Libdl.dlpath.

I don't know how large of an effort will be needed to get this working on 0.4 but I would rather file the issue than lose the information.

Activity

  1. joschu commented on Apr 16, 2015

    @joschu

    I fixed the problem mentioned by jpfairbanks, but there's another problem that looks more difficult to fix, whenever you try to run julia.Julia()--self.api.jl_call1 returns None:

    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "julia/core.py", line 304, in __init__
        for name, func in iteritems(base_functions(self)):
      File "julia/core.py", line 165, in base_functions
        names = julia.eval("names(Base)")
      File "julia/core.py", line 362, in eval
        "{}".format(src))
    julia.core.JuliaError: ErrorException in Julia
    
  2. leonardt commented on Jun 5, 2015

    @leonardt

    I threw this snippet at the end of eval (same code used in call)

            exoc = self.api.jl_exception_occurred()
            if not res and exoc:
                exception_type = self.api.jl_typeof_str(exoc).decode('utf-8')
                try:
                    exception_msg = self._capture_showerror_for_last_julia_exception()
                except UnicodeDecodeError:
                    exception_msg = "<couldn't get stack>"
                raise JuliaError(u'Exception \'{}\' in Julia PyObject:\n{}\n\nCode:\n{}'
                                 .format(exception_type, exception_msg, src))
    

    and the traceback gives me a MemoryError which seems rather odd.

    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/mnt/home/truongle/pyjulia/julia/core.py", line 300, in __init__
        for name, func in iteritems(base_functions(self)):
      File "/mnt/home/truongle/pyjulia/julia/core.py", line 165, in base_functions
        names = julia.eval("names(Base)")
      File "/mnt/home/truongle/pyjulia/julia/core.py", line 362, in eval
        .format(exception_type, exception_msg, src))
    julia.core.JuliaError: Exception 'MemoryError' in Julia PyObject:
    <couldn't get stack>
    
    Code:
    names(Base)
    
  3. leonardt commented on Jun 5, 2015

    @leonardt

    Just checked that running PyObject(names(Base)) in the Julia repl doesn't throw an error, so it seems in this environment something is different.

  4. bermanmaxim commented on Jul 2, 2015

    @bermanmaxim

    I tried modifying the embedding.c example of Julia, to make it call jl_eval_string("names(Base)");, to see if Julia API has trouble with that statement... But it works well (jl_eval_string("println(names(Base))"); prints a nice list of objects). After some humble digging, I am quite clueless...

  5. jakebolewski commented on Jul 7, 2015

    @jakebolewski
    Contributor

    I only use this for demos (and it gets updated usually when I have to give one), so it would be great to get a PR to support v0.4. Otherwise, this won't happen until 0.4 is released at the earliest.

  6. gabrielelanaro commented on Oct 14, 2015

    @gabrielelanaro

    @bermanmaxim I'm also stuck at that point, as you mentioned, the issue lies in jl_call1 function.

    We pass 2 void pointers, one is the function to be called (PyObject) and the other one is the argument (The result of Base(names))

    Now this call returns a NULL pointer (None, in ctypes terms), which means that probably we're using py_call1 in the wrong way

  7. sebastroy commented on Oct 30, 2015

    @sebastroy

    My guess is that the c_void_p (imported as void_p) is the culprit. I tried to call to jl_call1 from a C:

    #include <julia.h>
    
    int main(int argc, char *argv[])
    {
       /* required: setup the julia context */
       jl_init_with_image("/usr/lib/julia", "sys.so");
    
       /* run julia commands */
       jl_eval_string("using PyCall");
       jl_value_t *src = jl_eval_string("names(Base)");
       jl_value_t *pyo = jl_eval_string("PyObject");
    
       /* line below is equivalent to the python version in core.py eval function and fails  */
       jl_value_t *ret = jl_call1((void *)pyo,(void *)src);
    
       jl_atexit_hook(0);
       return 0;
     }
    

    and this is not working. I looked into the julia C library and no changes explains the rise of the problem. The eval function in pyjulia dates from the init commit so I doubt this is the problem. I have yet to make the eval C equivalent work properly. Could it be a change in ctypes? In the C julia API, the function throw an execption (with the same snippet as leonardt) but I get ReadOnlyMemoryError instead. If I call self.call("PyObject(names(Base))") it works, but you can't use the library if you can't marshall back to PyObject...

  8. ronisbr commented on Nov 5, 2015

    @ronisbr

    I am also seeing this behavior. Using the @sebastroy code, ret is NULL, which is not supposed to be. This is what I am also seeing in pyjulia.

    The same thing is happening if I try to run the code Int64(1) using the jl_call1 function. However, everything works if I use int64(1) instead. However, I got a message that this is deprecated.

    In the mean time, we can fix the problem using convert function as in the code below:

    #include <julia.h>
    
    int main(int argc, char *argv[])
    {
       /* required: setup the julia context */
       jl_init_with_image("/usr/lib64/julia", "sys.so");
    
       /* run julia commands */
       jl_eval_string("using PyCall");
       jl_value_t *src = jl_eval_string("1");
       jl_value_t *convert = jl_eval_string("convert");
       jl_value_t *pyobject = jl_eval_string("PyObject");
    
       jl_value_t *ret = (jl_value_t*)jl_call2((void *)convert, (void *)pyobject, (void *)src);
    
       jl_atexit_hook(0);
       return 0;
     }
    

    In this case, ret is not NULL anymore.
    Using a similar approach, I could call julia functions in Python through ctypes.

  9. ronisbr commented on Nov 5, 2015

    @ronisbr

    Hi guys!

    According to this: JuliaLang/julia#13882 the old pyjulia code of using jl_call1 with PyObject and a result will not work anymore. Instead, it is now necessary to use convert function.

  10. yuyichao commented on Nov 5, 2015

    @yuyichao

    Just to be clear, if you just want to convert something to a certain type, you should always use the convert function, no matter which version you are on. If you want to call an object on 0.4 (which can be any objects), you should use jl_call* if it is a function and use the call (julia) function otherwise.

  11. sebastroy commented on Nov 5, 2015

    @sebastroy

    Awesome thanks!

  12. sebastroy commented on Nov 17, 2015

    @sebastroy

    @ronisbr I tried to back port the C code in core.py for pyjulia with no success. I fail to understand how to use convert within the python code to get pyjulia working again... My understanding is that the line:

    res = self.api.jl_call1(void_p(self.api.PyObject), void_p(ans))
    

    should now use convert instead of void_p (which is c_void_p import as void_p in the core.py script).

    The C line:

      jl_value_t *ret = (jl_value_t*)jl_call2((void *)convert, (void *)pyobject, (void *)src);
    

    could be translated (roughly) as

       res = self.api.jl_call2(void_p('convert'), void_p(self.api.PyObject), void_p(ans))
    

    with:

       self.api.convert  = self.call('convert')
    

    but I get a segfault...

    I also tried replacing the self.call to jl_call* with same results... I give it another try today and update if I get something going...

  13. sebastroy commented on Nov 17, 2015

    @sebastroy

    So typical error I get is that:

      res = self.api.jl_call2(void_p('convert'),void_p('PyObject'),void_p(src))
    

    which is as equivalent as I can understand to the C formulation gives python error: TypeError: cannot be converted to pointer.

  14. ronisbr commented on Nov 17, 2015

    @ronisbr

    The following code is working for me (julia 0.4.1):

    from ctypes import *
    import subprocess
    
    julia = PyDLL('/usr/lib64/libjulia.so', RTLD_GLOBAL)
    julia.jl_init_with_image.argtypes = [c_char_p, c_char_p]
    julia.jl_init_with_image(b'/usr/lib64/julia/',b'./sys.so')
    
    julia.jl_eval_string.argtypes = [c_char_p]
    julia.jl_eval_string.restype = c_void_p
    
    src = "using PyCall"
    julia.jl_eval_string(src.encode('utf-8'))
    
    src = 'convert'
    convert = julia.jl_eval_string(src.encode('utf-8'))
    
    src = 'PyCall.PyObject'
    julia.pyo = julia.jl_eval_string(src.encode('utf-8'))
    
    src =  "eye(3)"
    ret = julia.jl_eval_string(src.encode('utf-8'))
    
    julia.jl_call2.restype = c_void_p
    
    res = julia.jl_call2(c_void_p(convert), c_void_p(julia.pyo), c_void_p(ret))
    
    julia.jl_get_field.restype = c_void_p
    boxed_obj = julia.jl_get_field(c_void_p(res), b'o')
    julia.jl_unbox_voidpointer.restype = py_object
    pyobj = julia.jl_unbox_voidpointer(c_void_p(boxed_obj))
    pythonapi.Py_IncRef(py_object(pyobj))
    
    print(pyobj)
    

    The only problem I had with segfault was due to PyCall being precompiled using a different python version. The python version you use to run this program must be the same one that you used to precompile PyCall. To do that:

    1. Delete ~/.julia/lib
    2. Run in julia:
      2.1) ENV["PYTHON"] = " ... path to python ... "
      2.2) Pkg.build("PyCall")
      2.3) using PyCall

    This should precompile PyCall correctly. After that, I could successfully run the code I posted.

  15. benmoran commented on Nov 26, 2015

    @benmoran

    This C code compiled with gcc -o embedd -I/usr/include/julia -L/usr/lib/x86_64-linux-gnu/julia -Wl,-R/usr/lib/x86_64-linux-gnu/julia embedding.c -lm -ljulia and linked against my system Julia 0.4.1 works fine:

    
    int main()
    {
        jl_init("/usr/bin/");
    
        {
            // Simple running Julia code
    
            jl_eval_string("println(sqrt(2.0))");
            jl_eval_string("println(eval(:(using PyCall)))");
            jl_eval_string("println(@pyimport datetime)");
            jl_eval_string("println(datetime.date(2000,1,1))");
        }
    
        jl_atexit_hook(0);
        return 0;
    }
    
    

    yet the same calls made through ctypes fails. (I've added a check_error() function to retrieve the Julia error message).

    import ctypes, os
    from ctypes import c_char_p as char_p, c_void_p as void_p
    JULIA_HOME="/usr/lib/x86_64-linux-gnu/julia/"
    libjulia_path = os.path.join(JULIA_HOME, "libjulia.so")
    
    def check_error():
      api.jl_exception_occurred.restype = void_p
      exoc = api.jl_exception_occurred()
      if not exoc:
        return
      api.jl_stderr_obj.argtypes = []
      api.jl_stderr_obj.restype = void_p
      api.jl_exception_clear.restype = None
      api.jl_show.restype = None
      api.jl_show.argtypes = [void_p, void_p]
      api.jl_show(api.jl_stderr_obj(), exoc)
      api.jl_exception_clear()
    
    
    api = ctypes.PyDLL(libjulia_path, ctypes.RTLD_GLOBAL)
    api.jl_init.argtypes = [ctypes.c_char_p]
    api.jl_init("/usr/bin")
    api.jl_eval_string("println(eval(:(using PyCall)))");
    check_error()
    
    #api.jl_eval_string("println(@pyimport datetime)");
    #api.jl_eval_string("println(datetime.date(2000,1,1))");
    #api.jl_atexit_hook(0);
    

    If I call that with PYTHONVERBOSE=0 I see it make lots of imports successfully, finally dlopen the datetime.so, and then give the ImportError:

    dlopen("/usr/lib/python2.7/lib-dynload/datetime.x86_64-linux-gnu.so", 2);
    InitError(:PyCall,PyError (:PyCapsule_Import) <type 'exceptions.ImportError'>
    ImportError('PyCapsule_Import could not import module "datetime"',)
    

    So there is something different about calling the Julia API functions directly, vs through Python and ctypes. (Also, why does the older version of PyCall need an explicit call to pyinitialize() when called through ctypes, but not when it is imported in the Julia REPL?)

  16. benmoran commented on Nov 30, 2015

    @benmoran

    Further progress (thanks @antocuni). On Linux, /usr/bin/python is statically linked so there is no separate .so file to be included if we're running in that. The older version of PyCall I used with 0.3 does not always try to dlopen() libpython - if it is called from a Julia already embedded in a Python process, then it uses the global namespace to find the Python C-API symbols. That means we only have one Python interpreter state.

    The new version wants to always dlopen() libpython - it does this both at precompilation time and in init. Then if we are running inside a Python instance already, we get two interpreters and things are not working properly.

  17. antocuni commented on Dec 1, 2015

    @antocuni

    To better clarify @benmoran comment: on linux

    1. If /usr/bin/python is itself linked to libpython2.7.so, dlopen(NULL) and dlopen("libpython2.7.so") should both work (I don't have such a python binary at hand to try)
    2. IF /usr/bin/python has been statically linked to libpython2.7.so (which is the case on ubuntu but other distros might compile it differently) the only correct way to link with it at runtime is doing dlopen(NULL)
    3. In that case, if you dlopen("libpython2.7.so") you are bringing in ANOTHER copy of the python interpreter, whose symbols conflicts with the ones already loaded in the global namespace and thus they get mixed in. Bad things will happen. With RTLD_DEEPBIND you ensure that libpython2.7.so finds its own symbols inside itself: you are effectively bringing in two different python interpreters with different internal states, but this is a hack, and as soon as libpython2.7.so dlopens another library (e.g. an extension module), things will explode.

    On windows, it's a different story, because python.exe is ALWAYS a small stub and the code is always in python27.dll, so the correct way is indeed to dlopen("python27.dll").

    Note that you can even try to dlopen("libpython3.4.so") from within /usr/bin/python2.7: things will be even worse, of course. So, to summarize: on ubuntu, PyCall is currently doing (3) but it should do (2) when we are already inside a python interpeter.

    I wrote a small snippet of Python which showcases the problem. As you can see, in the "wrong" and "very-wrong" modes, Py_IsInitialized returns 0:

    import sys
    import cffi
    ffi = cffi.FFI()
    
    ffi.cdef("""
        const char* Py_GetVersion(void);
        int Py_IsInitialized(void);
    """)
    
    
    if sys.argv[1] == 'correct':
        lib = ffi.dlopen(None)
    elif sys.argv[1] == 'wrong':
        lib = ffi.dlopen("libpython2.7.so")
    elif sys.argv[1] == 'very-wrong':
        lib = ffi.dlopen("libpython3.4m.so.1")
    else:
        assert False
    
    cstring = lib.Py_GetVersion()
    print ffi.string(cstring)
    is_initialized = lib.Py_IsInitialized()
    print 'is initialized?', is_initialized
  18. nbecker commented on Dec 1, 2015

    @nbecker

    Appears to be dynamically linked on fedora 23 x86_64

    On Tue, Dec 1, 2015 at 5:59 AM, antocuni [email protected] wrote:

    To better clarify @benmoran https://github.com/benmoran comment: on
    linux

    If /usr/bin/python is itself linked to libpython2.7.so, dlopen(NULL)
    and dlopen("libpython2.7.so") should both work (I don't have such a
    python binary at hand to try)
    2.

    IF /usr/bin/python has been statically linked to libpython2.7.so
    (which is the case on ubuntu but other distros might compile it
    differently) the only correct way to link with it at runtime is doing
    dlopen(NULL)
    3.

    In that case, if you dlopen("libpython2.7.so") you are bringing in
    ANOTHER copy of the python interpreter, whose symbols conflicts with
    the ones already loaded in the global namespace and thus they get mixed in.
    Bad things will happen. With RTLD_DEEPBIND you ensure that
    libpython2.7.so finds its own symbols inside itself: you are
    effectively bringing in two different python interpreters with different
    internal states, but this is a hack, and as soon as libpython2.7.so
    dlopens another library (e.g. an extension module), things will explode.

    On windows, it's a different story, because python.exe is ALWAYS a small
    stub and the code is always in python27.dll, so the correct way is indeed
    to dlopen("python27.dll").

    Note that you can even try to dlopen("libpython3.4.so") from within
    /usr/bin/python2.7: things will be even worse, of course. So, to summarize:
    on ubuntu, PyCall is currently doing (3) but it should do (2) when we are
    already inside a python interpeter.

    I wrote a small snippet of Python which showcases the problem. As you can
    see, in the "wrong" and "very-wrong" modes, Py_IsInitialized returns 0:

    import sysimport cffi
    ffi = cffi.FFI()

    ffi.cdef(""" const char* Py_GetVersion(void); int Py_IsInitialized(void);""")

    if sys.argv[1] == 'correct':
    lib = ffi.dlopen(None)elif sys.argv[1] == 'wrong':
    lib = ffi.dlopen("libpython2.7.so")elif sys.argv[1] == 'very-wrong':
    lib = ffi.dlopen("libpython3.4m.so.1")else:
    assert False

    cstring = lib.Py_GetVersion()print ffi.string(cstring)
    is_initialized = lib.Py_IsInitialized()print 'is initialized?', is_initialized

    —
    Reply to this email directly or view it on GitHub
    #38 (comment).

    Those who don't understand recursion are doomed to repeat it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions