gpt4 book ai didi

java - 导入模块错误: calling python script using jython in a java program

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:23:35 24 4
gpt4 key购买 nike

我正在尝试在 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 文件是:

日历.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");

关于java - 导入模块错误: calling python script using jython in a java program,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25406813/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com