0

Jython に pyc ファイルをインポートしたいのですが、Jython の 'pycimport' モジュールを調べるように勧められましたが、これは実験的なモジュールであるため、コード例を取得できませんでした。このモジュールを Java で実装するのを手伝ってください。

4

2 に答える 2

1

pycimportモジュールをJavaで実装したいのはなぜですか?

モジュールの使用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年前に書いたので、誰も触れていないと思います。それ以降に使用するJythonの内部ではいくつかの変更がpycimportあったため、いくつかの問題が発生する可能性があります。そのコードを再検討するのは楽しいかもしれませんが、いつ時間がかかるかわからないので、約束はしません。

于 2011-07-14T22:12:01.587 に答える
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);
    }
}
于 2011-07-15T05:51:24.283 に答える