首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Java中调用和接收Python脚本的输出?

在Java中调用和接收Python脚本的输出?
EN

Stack Overflow用户
提问于 2012-04-11 06:40:52
回答 10查看 177.5K关注 0票数 63

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

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

注意: Java和Python之间的实际通信不是我试图解决的问题所必需的。然而,这是我能想到的唯一一种轻松执行所需操作的方法。

EN

回答 10

Stack Overflow用户

回答已采纳

发布于 2012-04-11 06:48:11

不知道我是否正确理解了您的问题,但是如果您可以从控制台调用Python可执行文件,并且只想用Java语言捕获它的输出,那么您可以在Java Runtime类中使用exec()方法。

代码语言:javascript
复制
Process p = Runtime.getRuntime().exec("python yourapp.py");

您可以阅读有关如何实际读取此资源的输出:http://www.devdaily.com/java/edu/pj/pj010016 import java.io.*;

代码语言:javascript
复制
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 exec项目)可以帮助您做到这一点。你可以在这里了解更多:

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

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

票数 75
EN

Stack Overflow用户

发布于 2012-04-11 07:29:02

您可以将Jython库包含在您的Java项目中。您可以从Jython项目本身执行download the source code

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

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

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

代码语言:javascript
复制
for i in range(1,10):
    print(i)

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

代码语言:javascript
复制
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()); 
}

输出结果为:

代码语言:javascript
复制
1
2
3
4
5
6
7
8
9

只要您的Python脚本与Python2.5兼容,在Jython中运行它就不会有任何问题。

票数 33
EN

Stack Overflow用户

发布于 2016-10-11 17:05:49

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

JPserve提供了一种简单的方式来调用Python并将结果转换为格式良好的JSON,性能损失很小。以下是示例代码。

首先,在Python端启动jpserve

代码语言:javascript
复制
>>> from jpserve.jpserve import JPServe
>>> serve = JPServe(("localhost", 8888))
>>> serve.start()

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

然后从Java端调用Python:

代码语言:javascript
复制
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
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10097491

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档