【问题标题】:Java with Jython, elegant way to solve path trouble?Java 与 Jython,优雅的解决路径问题的方法?
【发布时间】:2012-07-05 15:29:57
【问题描述】:

我有一段 Java 代码,使用 Jython 调用一些 Python 库,这个库依赖于外部 Jython 经典库,如 re 用于正则表达式等,所以我有这种代码:

    PythonInterpreter interpreter = new PythonInterpreter(null, new PySystemState()); 
    PySystemState sys = Py.getSystemState(); 

    // below: so that my own library find necessary 'batteries included' Python libs
    sys.path.append(new PyString("C:/jython2.5.2/Lib")); // (path1)
    // below: i put my own Python library inside the Java package for clarity
    // and be able to package everything in jar, well, maybe is it no a good idea?
    // also i am wondering, because myfile.py remain inside /src subdirectories 
    // while after compiling Eclipse will put most in /bin subidrectories but not the *.py files
    // thus doing some:
    //    MyJythonFactory..class.getProtectionDomain().getCodeSource().getLocation().toString() 
    // will not help to rebuild the ..myJavaProject/src/my/domain/mypackage
    sys.path.append(new PyString("D:/eclipseWorkspace/myJavaProject/src/my/domain/mypackage")); (path2)

    interpreter.exec("from mylib import myfunc"); //(A)
    PyObject myPyFunction = interpreter.get("myfunc");

顺便说一句,我不喜欢我需要更改和硬编码路径 (path1)(path2) 的事实

您是否发现了一种避免这种情况并添加一些“whereami”自动检测路径功能的优雅方法(至少对于(path2))?

看起来我需要 (path1) 和 (path2) => 以便 (A) 工作!

我还可以将我的问题重新表述为没有任何 ImportError: No module named myModule 或如何避免硬编码类似以下内容的优雅方式:

 PySystemState sys = Py.getSystemState(); 
 sys.path.append("where/my/python/libs/live/while/they/are/at/the/same/place/as/my/current/java/class")

最好的问候

【问题讨论】:

  • 你不需要硬编码C:/jython2.5.2/Lib;正确安装的jython.jar 应该知道它的位置。
  • 好吧,我已经知道了,因为如果没有它就无法工作,请问有哪些步骤是我可能错过的,所以它没有“正确安装”?谢谢
  • 我刚刚运行了安装程序脚本,它运行起来没有任何问题。您是否移动了安装?
  • 实际上它可以工作,但是在mypythonmodules.py 内部,我有例如import re 模块和其他模块,看起来我需要为Jython.jar 提供这些库的路径,这就是为什么我以添加此路径结束。见:stackoverflow.com/questions/471000/jython-and-python-modules

标签: java import jython sys.path


【解决方案1】:

确保您的项目类路径中有jython-standalone.jar 而不是jython.jar,因为jython-standalone.jar 在 jar 中包含 Python Lib,因此您不需要将其附加到 sys.path。

如果您使用的是 maven,可以将其添加到 pom.xml

<dependency>
    <groupId>org.python</groupId>
    <artifactId>jython-standalone</artifactId>
    <version>2.7.0</version>
</dependency>

或者你可以下载jarhere

为你自己的python模块把它放在java项目的classpath中,Jython使用java classplath作为__pyclasspath__,这样你就避免了硬编码。

【讨论】:

    猜你喜欢
    • 2010-10-04
    • 1970-01-01
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-15
    • 2020-04-10
    • 2018-04-28
    相关资源
    最近更新 更多