【问题标题】:Bundling python files inside jar for access via jython在 jar 中捆绑 python 文件以通过 jython 访问
【发布时间】:2011-09-09 18:13:14
【问题描述】:

在下面的代码中,我只是使用 jython 从 java 代码中执行 test.py

public static void main(String[] args) {
  org.python.util.PythonInterpreter python = new org.python.util.PythonInterpreter();
  python.execfile("test.py");
  ...

我的问题是 test.py 需要与运行 jar 文件的目录位于同一目录中。
我需要这个 test.py 捆绑在 jar 中,并且仍然能够使用 jython 执行它。

How do you invoke a python script inside a jar file using python? 中建议的使用 ClassLoader 类中的 getResourceAsStream 方法读取字符串中的脚本的方法对我不起作用,因为我的 test.py 导入了更多捆绑在 jar 中的 python 脚本。

刚接触 java 和 jython 我真的很困惑。
任何帮助将不胜感激..!

【问题讨论】:

    标签: java python jar jython


    【解决方案1】:

    您可以简单地将 test.py 放在 jar 的根目录下,其他脚本的组织方式与普通 python 中的 fs 相同。 然后你可以这样做:

    public static void main(String[] args) {
      org.python.util.PythonInterpreter python = new org.python.util.PythonInterpreter();
      python.exec("import test");
      python.exec("test.callsomthing()");
    }
    

    test.py 中的导入应该正常工作,包括从 test.py 导入其他模块。

    【讨论】:

    • 谢谢!!你知道如何使用 netbeans 将文件放在 jar 的根目录下吗? (对不起,我以前没有用过jar包装)
    • stackoverflow.com/questions/3955299/… 获得了如何在 jar 的根目录下添加。非常感谢!! stackoverflow 岩石:)
    • @Daniel 我面临 ImportError: no module named test class test: def __init__(self): pass def hello(self): print("Hello Python function call..!")test.py 在同一个文件夹中。
    【解决方案2】:

    使用类的“getResourceAsStream”从jar中提取python文件。

    例如:http://fiji.sc/wiki/index.php/Jython_Scripting#Distributing_jython_scripts_in_a_.jar_file

    【讨论】:

    • 我了解您的建议是读取字符串中的整个 python 文件,然后按照stackoverflow.com/questions/2551269/… 中的建议执行它。但问题是我有多个 python 模块,所以 jar 中有更多的 python 模块是从这个 test.py 导入的,它们不会以这种方式工作。
    • @Nullpoet,PythonInterpreter 类具有执行文件的方法,对于只声明函数和类的脚本,这相当于加载它。因此,将它们全部加载到同一个 PythonInterpreter 实例中,然后执行依赖于其他实例的脚本。另一种方法是将所有 .py 文件复制到一个临时目录,然后将该目录添加到类路径中:from sys import path; path.append('/path/to/temp/dir')
    猜你喜欢
    • 2015-03-23
    • 2023-03-26
    • 2016-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多