遵循在Java应用程序中使用Jython,我可以集成Java和Jython (Java方法可以调用python脚本)。python代码位于py
目录中。Jython使用sys.path.append("py")
命令查找Jython脚本。
然后,我尝试将所有文件集成到一个jar文件中。
对于前一步,我可以生成一个jar文件,并将py目录与jar文件一起复制,它可以正常工作。我使用IntelliJ的思想来生成jar文件。
│ └── py
│ ├── Context$py.class
│ ├── Context.py
│ ├── Host$py.class
│ └── Host.py
├── aggregationPython.jar <-- Generated jar file
接下来,我尝试在jar文件中复制py目录,我也使用了IntelliJ。
我检查了jar文件中的py目录。您可以看到py目录位于jar文件的根目录。
但是,当我执行jar文件时,我发现了一个错误,说明缺少jython模块。
> java -jar aggregationPython.jar
Exception in thread "main" ImportError: No module named Host
可能出什么事了?我假设py目录可以存储在jar文件中,就像在jar文件之外找到的那样。这个假设有什么不对?
发布于 2014-02-11 11:31:17
Jython类文件位于jar文件中,Jython的搜索路径并不关心它们是否在jar文件中。我们所需要的只是定位Jython类的位置,并让Jython知道它。
根据这个帖子(如何获得正在运行的JAR文件的路径?)的提示,您可以找到jar文件所在的路径。类文件可以在location + "py“目录中找到。
出于开发目的,还应该指定源目录中的Jython源代码("src/py")。
String runningDir = Simulate.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String jarPointer = "py";
String joinedPath = new File(runningDir, jarPointer).toString();
String pythonSrcPath = "/Users/smcho/code/PycharmProjects/aggregator/src";
JythonObjectFactory.setupPath(new String[]{joinedPath, "src/py"});
修改后,Jython可以正确地找到类。
这是用于设置Jython路径的setupPath
方法。
public static void setupPath(String[] paths)
{
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import sys;");
for (int i = 0; i < paths.length; i++) {
interpreter.exec(String.format("sys.path.append(\"%s\")", paths[i]));
}
}
https://stackoverflow.com/questions/21708972
复制相似问题