使用Jython在Java中运行Python程序

3
我编写了一个由五个.py脚本文件组成的Python程序。 我想从Java应用程序中执行其中的主要Python脚本。
有哪些选项可以实现此目标?使用PythonInterpreter不起作用,因为例如无法从Jython加载datetime模块(我不希望用户确定其Python路径以使这些依赖项正常工作)。
我使用Jython的compileall将整个文件夹编译为.class文件。 我可以将这些.class文件嵌入以某种方式执行Java应用程序中的主文件,还是该如何进行?

我认为Jython是让你可以将Java工具集成到Python中,而不是反过来... - OneCricketeer
@cricket_007 Jython是JVM的Python实现。你可以主要使用任何一种语言进行编程和互操作。 - chrylis -cautiouslyoptimistic-
如何从Java调用.vbs文件并使该.vbs文件调用Python文件? - raviraja
3个回答

1
请查看Java中的ProcessBuilder类: https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html
在Java构造函数中使用的命令应与在命令行中键入的命令相同。例如:
Process p = new ProcessBuilder("python", "myScript.py", "firstargument").start();

进程构建器(Process Builder)与Python的subprocess模块执行相同的操作。

请查看通过Process Builder运行脚本

注:关于Jython部分的问题,如果您访问Jython网站(请参阅其网站www.jython.org的FAQ部分),请检查“从Java使用Jython”的条目。


在这种情况下,我需要确保用户安装了Python 2.x以使我的脚本正常工作,并将其注册为“python”命令,最后我需要将脚本提取到硬盘的某个地方。但这不是我想要的,我会看看Jython。 - CrushedPixel
尽管这是有用的信息,但似乎并没有直接回答如何使用Python代码从Java/Jython中绕过已安装的Python运行时的问题。请参阅我的帖子 - Big Rich

1
我也对在Java中直接运行Python代码很感兴趣,使用Jython,避免安装Python解释器的需要。
文章'将Jython嵌入Java应用程序'解释了如何引用外部*.py Python脚本,并传递参数,无需安装Python解释器。
#pymodule.py - make this file accessible to your Java code
def square(value):
return value*value

此函数可以通过创建执行它的字符串,或者获取指向该函数的指针并使用正确的参数调用其“call”方法来执行。
//Java code implementing Jython and calling pymodule.py
import org.python.util.PythonInterpreter;
import org.python.core.*;

public class ImportExample {
   public static void main(String [] args) throws PyException
   {
       PythonInterpreter pi = new PythonInterpreter();
       pi.exec("from pymodule import square");
       pi.set("integer", new PyInteger(42));
       pi.exec("result = square(integer)");
       pi.exec("print(result)");
       PyInteger result = (PyInteger)pi.get("result");
       System.out.println("result: "+ result.asInt());
       PyFunction pf = (PyFunction)pi.get("square");
       System.out.println(pf.__call__(new PyInteger(5)));
   }
}

我的上面的回答更符合在Python脚本中执行特定函数的情况。https://stackoverflow.com/a/36288406/304330上的答案明确解释了如何通过Jython将参数传递给Python脚本,就像从CLi(不了解脚本内部,只了解命令行)一样。我可能会修改我的答案以反映这些新信息。 - Big Rich

0

加载其他模块是可能的。您只需指定Python路径,以便找到您的自定义模块。请参考以下测试案例,我正在在调用函数(my_maths())中使用Python的datatime/math模块,并且我有多个Python文件位于python.path中被main.py导入。

@Test
public void testJython() {

    Properties properties = System.getProperties();
    properties.put("python.path", ".\\src\\test\\resources");
    PythonInterpreter.initialize(System.getProperties(), properties, new String[0]);

    PythonInterpreter interpreter = new PythonInterpreter();
    interpreter.execfile(".\\src\\test\\resources\\main.py");

    interpreter.set("id", 150); //set variable value
    interpreter.exec("val = my_maths(id)"); //the calling function in main.py

    Integer returnVal = (Integer) interpreter.eval("val").__tojava__(Integer.class);
    System.out.println("return from python: " + returnVal);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接