用Java中的Python脚本调用和接收输出? [英] Call and receive output from Python script in Java?

查看:504
本文介绍了用Java中的Python脚本调用和接收输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What's the easiest way to execute a Python script from Java, and receive the output of that script? I've looked for different libraries like Jepp or Jython, but most appear out of date. Another problem with the libraries is that I need to be able to easily include a library with the source code (though I don't need to source for the library itself) if I use a library.

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

Because of this, would the easiest/most effective way be to simply do something like call the script with runtime.exec, and then somehow capture printed output? Or, even though it would be very painful for me, I could also just have the Python script output to a temporary text file, then read the file in Java.

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

Note: the actual communication between Java and Python is not a requirement of the problem I am trying to solve. This is, however, the only way I can think of to easily perform what needs to be done.

推荐答案

不确定我是否理解你的问题,但前提是你可以从控制台调用Python可执行文件而只是想使用Java捕获其输出,您可以在Java Runtime 类中使用 exec()方法。

Not sure if I understand your question correctly, but provided that you can call the Python executable from the console and just want to capture its output in Java, you can use the exec() method in the Java Runtime class.

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

您可以在这里阅读如何实际读取输出:

You can read up on how to actually read the output here:

http://www.devdaily.com/java/edu/pj/pj010016

还有一个Apache库(Apache exec项目)可以帮助您解决这个问题。你可以在这里阅读更多相关信息:

There is also an Apache library (the Apache exec project) that can help you with this. You can read more about it here:

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

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

这篇关于用Java中的Python脚本调用和接收输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆