Search code examples
pythonjythonpyc

How to use "pycimport" module of Jython?


I want to import a pyc file in Jython, and I was suggested to explore the 'pycimport' module in Jython, but since this is an experimental module , I was not able to get any code examples, I would be very glad if anybody can help me to implement this module in Java.


Solution

  • Why do you want to implement the pycimport module in Java?

    Using the pycimport module is actually quite simple, you just import the module, and after that you can import modules in pyc-files:

    cole:tmp tobias$ cat mymodule.py
    def fibonacci(n):
        a,b = 1,0
        for i in range(n):
            a,b = a+b,a
        return a
    
    cole:tmp tobias$ python
    Python 2.7 (r27:82508, Jul  3 2010, 21:12:11) 
    [GCC 4.0.1 (Apple Inc. build 5493)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> from mymodule import fibonacci
    >>> fibonacci(4)
    5
    >>> fibonacci(5)
    8
    >>> ^D
    cole:tmp tobias$ ls mymodule.*
    mymodule.py mymodule.pyc
    cole:tmp tobias$ mv mymodule.py xmymodule.pyx
    cole:tmp tobias$ jython
    Jython 2.5.2rc4 (trunk:7202, Feb 24 2011, 14:31:12) 
    [Java HotSpot(TM) 64-Bit Server VM (Apple Inc.)] on java1.6.0_26
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import pycimport
    >>> from mymodule import fibonacci
    >>> fibonacci(4)
    5
    >>> fibonacci(5)
    8
    >>> ^D
    

    Just to show that pycimport does infact import from the pyc-file:

    cole:tmp tobias$ jython
    Jython 2.5.2rc4 (trunk:7202, Feb 24 2011, 14:31:12) 
    [Java HotSpot(TM) 64-Bit Server VM (Apple Inc.)] on java1.6.0_26
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import mymodule
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ImportError: No module named mymodule
    >>> import pycimport              
    >>> import mymodule 
    >>> mymodule.__file__
    'mymodule.pyc'
    >>> ^D
    

    As you note though, the pycimport module is experimental. I don't think anyone has touched it since I wrote it 4 years ago. A few things have changed in the Jython internals that pycimport uses since then, so there might be a few issues in it. It could be fun to revisit that code, but I don't know when I would have time, so I will not make any promises.