繁体   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