将数据从 Java 进程传递到 python 脚本 [英] Passing data from Java process to a python script
问题描述
我将一个外部 Python 脚本称为 Java 进程,并希望向其发送数据.我创建了一个进程并尝试发送一个字符串.稍后,python 脚本应该等待来自 Java 的新输入,处理这些数据并再次等待(同时真正循环).
I call a external Python script as Java process and want to send data to this. I create a process and try to send a string. Later the python script should wait for a new input from Java, work with this data and wait again(while true loop).
Python 代码 (test.py):
input = input("")
print("Data: " + input)
Java 代码:
Process p = Runtime.getRuntime().exec("py ./scripts/test.py");
BufferedWriter out = new BufferedWriter(new
OutputStreamWriter(p.getOutputStream()));
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
System.out.println("Output:");
String s = null;
out.write("testdata");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
简单打印的处理和输出有效,但不适用于 input
和 BufferedWriter
.是否可以使用 Java 进程将数据发送到此 python 输入?
The process and output of simple prints works, but not with input
and BufferedWriter
.
Is it possible to send data to this python input with a Java process?
我阅读了其他解决方案:
I read from other solutions:
- 创建一个 Python 监听器并向这个脚本发送消息
- 将外部脚本导入 Jython 并传递数据
这是处理我的问题的更好解决方案吗?
Are this better solutions to handle my problem?
推荐答案
在java中使用Process类
use Process class in java
什么是进程类?此类用于启动 .exe 或任何使用 java 的脚本
what is process class ? this class is used to start a .exe or any script using java
它可以如何帮助您创建您的 python 脚本以接受命令行变量并将您的数据从 java 类发送到 python 脚本.
How it can help you Create your python script to accept command line variables and send your data from java class to python script.
例如:
System.out.println("Creating Process");
ProcessBuilder builder = new ProcessBuilder("my.py");
Process pro = builder.start();
// wait 10 seconds
System.out.println("Waiting");
Thread.sleep(10000);
// kill the process
pro.destroy();
System.out.println("Process destroyed");
这篇关于将数据从 Java 进程传递到 python 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!