簡體   English   中英

導入模塊錯誤:在java程序中使用jython調用python腳本

[英]import module error: calling python script using jython in a java program

我試圖在java程序中使用jython從netbeans執行python文件。 我的代碼是這樣的:

PythonInterpreter.initialize(System.getProperties(), System.getProperties(), 
                             new String[0]);
PythonInterpreter interp = new PythonInterpreter();
interp.execfile("as1.py");

錯誤是:

Traceback (most recent call last):
  File "as1.py", line 2, in <module>
    import datetime
ImportError: No module named datetime

以及相互依賴的python文件也沒有導入它們在同一目錄中。

喜歡:

PythonInterpreter.initialize(System.getProperties(), System.getProperties(), new String[0]);
PythonInterpreter interp = new PythonInterpreter();
interp.execfile("calen.py");

python文件是:

calen.py:

from as1 import * 
print ( "I am printing" + str(Moh(1000).run()))

as1.py:

from time import time
import datetime
class Moh:
    def __init__(self, n):  
        self.n = n

    def run(self):
        data = [1,2,3,4,5]
        start = time()
        for i in range(self.n):
            data.append(i)
        end = time()
        return ( end - start )/self.n

if __name__ == "__main__":
    print ( "I am printing" + str(Moh(1000).run()))

錯誤是:

Traceback (most recent call last):
  File "calen.py", line 1, in <module>
    from as1 import * 
ImportError: No module named as1

必須為PythonInterpreter設置“python.path”,以便它可以加載as1模塊。 為此,您必須以這種方式初始化PythonInterpreter:

Properties properties = System.getProperties();
properties.put("python.path", PATH_TO_PARENT_DIRECTORY_OF_AS1_PY);
PythonInterpreter.initialize(System.getProperties(), properties, new String[0]);
PythonInterpreter interp = new PythonInterpreter();
interp.execfile("calen.py");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM