Rod*_*Rod 3 python java interaction interface
我有一个python应用程序,我不能从我的角度编辑它的黑盒子.python应用程序知道如何处理文本并返回已处理的文本.我有另一个用Java编写的应用程序,它知道如何收集未处理的文本.
当前状态,python应用程序每隔x分钟以批处理模式工作.
我想制作python
处理部分过程:Java应用程序收集文本并请求python应用程序处理并返回已处理的文本作为流程的一部分.
您认为最简单的解决方案是什么?
谢谢,罗德
使用ProcessBuilder作为过滤器执行Python代码:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class PBTest {
public static void main(String[] args) {
ProcessBuilder pb = new ProcessBuilder(
"python3", "-c", "print(42)");
pb.redirectErrorStream(true);
try {
Process p = pb.start();
String s;
BufferedReader stdout = new BufferedReader(
new InputStreamReader(p.getInputStream()));
while ((s = stdout.readLine()) != null) {
System.out.println(s);
}
System.out.println("Exit value: " + p.waitFor());
p.getInputStream().close();
p.getOutputStream().close();
p.getErrorStream().close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我对Jython之类的东西一无所知.我想这是最好的解决方案,如果你可以在每次Java应用程序需要转换文本时执行两个程序而不执行新进程.无论如何,一个简单的概念证明就是从Java App执行一个单独的过程以使其工作.接下来,您可以使用所有工具增强执行.
从Java执行单独的进程
String[] envprops = new String[] {"PROP1=VAL1", "PROP2=VAL2" };
Process pythonProc = Runtime.getRuntime().exec(
"the command to execute the python app",
envprops,
new File("/workingdirectory"));
// get an outputstream to write into the standard input of python
OutputStream toPython = pythonProc.getOutputStream();
// get an inputstream to read from the standard output of python
InputStream fromPython = pythonProc.getInputStream();
// send something
toPython.write(.....);
// receive something
fromPython.read(....);
Run Code Online (Sandbox Code Playgroud)
重要:字符不是字节
很多人都很清楚这一点.
注意char到字节的转换(记住Writers/Readers用于字符,Input/OutputStreams用于字节,convertir用于编码是必需的,你可以OuputStreamWriter用来将字符串转换为字节并发送,InputStreamReader将字节转换为字符和读取他们).
| 归档时间: |
|
| 查看次数: |
4690 次 |
| 最近记录: |