如何使用Jython的“pycimport”模块?

时间:2011-07-14 05:58:21

标签: python jython pyc

我想在Jython中导入一个pyc文件,我建议在Jython中探索'pycimport'模块,但由于这是一个实验模块,我无法获得任何代码示例,我会很高兴如果有人可以帮我用Java实现这个模块。

2 个答案:

答案 0 :(得分:1)

为什么要在Java中实现pycimport模块?

使用pycimport模块实际上非常简单,只需导入模块,然后就可以在pyc文件中导入模块了:

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

只是为了表明pycimport确实从pyc文件中导入:

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

正如您所注意到的,pycimport模块是实验性的。自从我4年前写这篇文章以来,我认为没有人接触过它。在pycimport之后使用的Jython内部中发生了一些变化,因此可能存在一些问题。重新访问该代码可能很有趣,但我不知道何时有时间,所以我不会做出任何承诺。

答案 1 :(得分:0)

这就是我做的方式:)

名为shams.pyc的pyc文件位于C:\ PyTest \,其相应的.py文件内容如下:

shams.py

class test:

    def call_helloworld(self) :
        return "Hello World"

test.java

import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.util.PythonInterpreter;

import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.util.PythonInterpreter;
public class test{ 
    public static void main(String[] args) {
        PythonInterpreter interpreter = new PythonInterpreter();
        PythonInterpreter.initialize(System.getProperties(),System.getProperties(), new String[0]); 
        interpreter.exec("import sys");
        interpreter.exec("sys.path.append('C:\\PyTest')"); 
        interpreter.exec("import pycimport");
        interpreter.exec("import shams");
        interpreter.exec("from shams import test");
        PyObject pyClass = interpreter.get("test");
        PyString real_result = (PyString) pyClass.invoke("call_helloworld",pyClass.__call__());
        System.out.println(real_result);
    }
}