繁体   English   中英

从 Java 中的 Python 脚本调用并接收 output?

[英]Call and receive output from Python script in Java?

从 Java 执行 Python 脚本并接收该脚本的 output 的最简单方法是什么? 我寻找过不同的库,如 Jepp 或 Jython,但大多数都已过时。 库的另一个问题是,如果我使用一个库,我需要能够轻松地将一个库包含在源代码中(尽管我不需要为库本身提供源代码)。

因此,最简单/最有效的方法是简单地做一些事情,比如用 runtime.exec 调用脚本,然后以某种方式捕获打印的 output? 或者,即使这对我来说会很痛苦,我也可以将 Python 脚本 output 保存到临时文本文件中,然后读取 Java 中的文件。

注意:Java 和 Python 之间的实际通信不是我要解决的问题的要求。 然而,这是我能想到的轻松执行需要完成的工作的唯一方法。

不确定我是否正确理解你的问题,但前提是你可以从控制台调用 Python 可执行文件并且只想在 Java 中捕获它的 output,你可以在 Java Runtime class 中使用exec()方法。

Process p = Runtime.getRuntime().exec("python yourapp.py");

您可以从以下资源中了解如何实际读取 output: http://www.devdaily.com/java/edu/pj/pj010016 import java.io.*;

public class JavaRunCommand {

    public static void main(String args[]) {

        String s = null;

        try {
            
        // run the Unix "ps -ef" command
            // using the Runtime exec method:
            Process p = Runtime.getRuntime().exec("ps -ef");
            
            BufferedReader stdInput = new BufferedReader(new 
                 InputStreamReader(p.getInputStream()));

            BufferedReader stdError = new BufferedReader(new 
                 InputStreamReader(p.getErrorStream()));

            // read the output from the command
            System.out.println("Here is the standard output of the command:\n");
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }
            
            // read any errors from the attempted command
            System.out.println("Here is the standard error of the command (if any):\n");
            while ((s = stdError.readLine()) != null) {
                System.out.println(s);
            }
            
            System.exit(0);
        }
        catch (IOException e) {
            System.out.println("exception happened - here's what I know: ");
            e.printStackTrace();
            System.exit(-1);
        }
    }
}

还有一个 Apache 库(Apache 执行项目)可以帮助您解决这个问题。 你可以在这里读更多关于它的内容:

http://www.devdaily.com/java/java-exec-processbuilder-process-1

http://commons.apache.org/exec/

您可以在 Java 项目中包含Jython库。 您可以从 Jython 项目本身下载源代码

Jython 确实提供了对JSR-223 的支持,它基本上允许您从 Java 运行 Python 脚本。

您可以使用ScriptContext来配置要将执行的 output 发送到的位置。

例如,假设您在名为numbers.py的文件中有以下 Python 脚本:

for i in range(1,10):
    print(i)

因此,您可以从 Java 运行它,如下所示:

public static void main(String[] args) throws ScriptException, IOException {

    StringWriter writer = new StringWriter(); //ouput will be stored here
    
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptContext context = new SimpleScriptContext();
    
    context.setWriter(writer); //configures output redirection
    ScriptEngine engine = manager.getEngineByName("python");
    engine.eval(new FileReader("numbers.py"), context);
    System.out.println(writer.toString()); 
}

output 将是:

1
2
3
4
5
6
7
8
9

只要您的 Python 脚本与 Python 2.5 兼容,您就可以使用 Jython 运行它。

我以前遇到过同样的问题,也在这里阅读了答案,但没有找到任何令人满意的解决方案可以平衡兼容性、性能和格式化 output,Jython 不能使用扩展 C 包并且比 CPython 慢。 所以最后我决定自己发明轮子,花了我5个晚上,希望对你也有帮助:jpserve( https://github.com/johnhuang-cn/jpserve )。

JPserve 提供了一种简单的方法来调用 Python 并通过格式化 JSON 交换结果,性能损失很小。 以下是示例代码。

首先,在Python端启动jpserve

>>> from jpserve.jpserve import JPServe
>>> serve = JPServe(("localhost", 8888))
>>> serve.start()

INFO:JPServe:JPServe starting...
INFO:JPServe:JPServe listening in localhost 8888

然后从JAVA端调用Python:

PyServeContext.init("localhost", 8888);
PyExecutor executor = PyServeContext.getExecutor();
script = "a = 2\n"
    + "b = 3\n"
    + "_result_ = a * b";

PyResult rs = executor.exec(script);
System.out.println("Result: " + rs.getResult());

---
Result: 6

我寻找过不同的库,如 Jepp 或 Jython,但大多数似乎都已经过时了。

Jython 不是“图书馆”; 它是 Java 虚拟机之上的 Python 语言的实现。 它绝对不会过时; 最近一次发布是今年 2 月 24 日。 它实现了 Python 2.5,这意味着您将缺少一些较新的功能,但老实说它与 2.7 没有太大区别。

注意:Java 和 Python 之间的实际通信不是上述作业的要求,所以这不是我的功课。 然而,这是我能想到的轻松执行需要完成的工作的唯一方法。

这对于学校作业来说似乎不可能。 请告诉我们更多关于您真正想做的事情。 通常,学校作业会明确指定您将使用哪种语言来做什么,而且我从未听说过涉及一种以上语言的作业。 如果是这样,他们会告诉你是否需要建立这种沟通方式,以及他们打算如何进行。

Jep是另一种选择。 它通过JNI在Java中嵌入了CPython

import jep.Jep;
//...
    try(Jep jep = new Jep(false)) {
        jep.eval("s = 'hello world'");
        jep.eval("print(s)");
        jep.eval("a = 1 + 2");
        Long a = (Long) jep.getValue("a");
    }

Jython 方法

Java 应该是独立于平台的,调用本机应用程序(如 python)并不是非常独立于平台。

Java 中有一个 Python (Jython) 版本,它允许我们将 Python 嵌入到我们的 Java 程序中。 通常,当您要使用外部库时,一个障碍是正确编译和运行它,因此我们 go 完成了使用 Jython 构建和运行一个简单程序 Java 的过程。

我们首先获取 jython jar 文件:

https://www.jython.org/download.html

我将 jython-2.5.3.jar 复制到我的 Java 程序所在的目录中。 然后我输入了下面的程序,它和前两个程序一样; 取两个数字,将它们发送到 python,后者将它们相加,然后 python 将其返回给我们的 Java 程序,其中数字输出到屏幕:

import org.python.util.PythonInterpreter; 
import org.python.core.*; 

class test3{
    public static void main(String a[]){

        PythonInterpreter python = new PythonInterpreter();

        int number1 = 10;
        int number2 = 32;
        python.set("number1", new PyInteger(number1));
        python.set("number2", new PyInteger(number2));
        python.exec("number3 = number1+number2");
        PyObject number3 = python.get("number3");
        System.out.println("val : "+number3.toString());
    }
}

我将此文件称为“test3.java”,保存它,然后执行以下操作来编译它:

javac -classpath jython-2.5.3.jar test3.java

下一步是尝试运行它,我按以下方式执行:

java -classpath jython-2.5.3.jar:. test3

现在,这允许我们以平台无关的方式使用 Java 中的 Python。 这有点慢。 尽管如此,它还是很酷,它是一个用 Java 编写的 Python 解释器。

ProcessBuilder 非常易于使用。

ProcessBuilder pb = new ProcessBuilder("python","Your python file",""+Command line arguments if any);
Process p = pb.start();

这应该调用 python。请参阅此处的流程方法以获取完整示例!

https://bytes.com/topic/python/insights/949995-three-ways-run-python-programs-java

您可以尝试使用 groovy。它在 JVM 上运行,并且非常支持运行外部进程和提取 output:

http://groovy.codehaus.org/Executing+External+Processes+From+Groovy

您可以在取自同一链接的这段代码中看到 groovy 如何使获取进程状态变得容易:

println "return code: ${ proc.exitValue()}"
println "stderr: ${proc.err.text}"
println "stdout: ${proc.in.text}" // *out* from the external program is *in* for groovy

首先,我建议使用 ProcessBuilder(自 1.5 起)
这里描述了简单的用法
https://stackoverflow.com/a/14483787
有关更复杂的示例,请参阅
http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html

我在从 Java 启动 Python 脚本时遇到了问题,脚本产生了太多的 output 到标准输出,一切都变坏了。

实现的最佳方法是使用 Apache Commons Exec,因为我将它用于生产,即使对于 Java 8 环境也没有问题,因为它允许您以synchronousasynchronous方式执行任何外部进程(包括 python、bash 等)使用看门狗。

 CommandLine cmdLine = new CommandLine("python");
 cmdLine.addArgument("/my/python/script/script.py");
 DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

 ExecuteWatchdog watchdog = new ExecuteWatchdog(60*1000);
 Executor executor = new DefaultExecutor();
 executor.setExitValue(1);
 executor.setWatchdog(watchdog);
 executor.execute(cmdLine, resultHandler);

 // some time later the result handler callback was invoked so we
 // can safely request the exit value
 resultHandler.waitFor();

此处共享了一个小而完整的 POC 的完整源代码,解决了本文中另一个问题;

https://github.com/raohammad/externalprocessfromjava.git

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM