简体   繁体   English

Java Processbuilder流到Python脚本

[英]Java Processbuilder Stream to Python-Script

I have a minor Problem with a small Project I'm trying to do. 我正在尝试做的一个小项目有一个小问题。 I'm trying to use a Java-Program to call a Python-Script. 我正在尝试使用Java程序来调用Python脚本。

Java: Java的:

ProcessBuilder pb = new ProcessBuilder("python3", "tmp.py");
process = pb.start();

OutputStream stdin = process.getOutputStream();
InputStream stderr = process.getErrorStream();
InputStream stdout = process.getInputStream();

BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));

writer.write("example" + "\n");

String output = reader.readLine();

Python-Script tmp.py (example): Python脚本tmp.py(示例):

import sys

sys.stdin.readline()
print("Hello World")

It wont terminate, seemingly because sys.sdin.readline() isnt catching any input and if I remove this line it terminates just fine. 它不会终止,这似乎是因为sys.sdin.readline()不会捕获任何输入,如果我删除此行,它将终止就好了。 (stderror was empty too) I tried different things to fix this but nothing seems to work. (stderror也为空)我尝试了其他方法来解决此问题,但似乎没有任何效果。

I would really appreciate any advice. 我真的很感谢任何建议。 Thanks in advance. 提前致谢。

(Update: I tried to modify the Java-Program to access a .jar File instead of a Python-Script but the same error occurs here to. Using the Python Method subprocess.Popen() to access the Script however works just fine.) (更新:我试图修改Java程序以访问.jar文件而不是Python脚本,但是这里发生了相同的错误。使用Python方法subprocess.Popen()访问脚本却可以正常工作。)

Make sure you start python unbuffered with -u flag : 确保您使用-u标志无缓冲地启动python:

Force the binary layer of the stdout and stderr streams (which is available as their buffer attribute) to be unbuffered. 强制取消对stdout和stderr流的二进制层(可作为其缓冲属性使用)。 The text I/O layer will still be line-buffered if writing to the console, or block-buffered if redirected to a non-interactive file. 如果写入控制台,则文本I / O层仍将是行缓冲的;如果重定向到非交互式文件,则将保留块I / O的层。

Edit 编辑

I recommend reviewing the buffering all the same. 我建议同样检查缓冲。 The python unbuffered is a common one, but you possibly still have some buffering. python unbuffered是一种常见的方法,但是您可能仍然会有一些缓冲。 Make sure you flush java writer, writer.flush() . 确保刷新Java writer, writer.flush()

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

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