【发布时间】:2011-05-05 23:26:45
【问题描述】:
(我是 Java 新手) 我需要启动一个进程并接收 2 或 3 个句柄:用于 STDIN、STDOUT (和 STDERR),因此我可以将输入写入进程并接收其输出,就像命令行管道的行为方式(例如“grep”)
在 Python 中,这是通过以下代码实现的:
from subprocess import Popen, PIPE
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE)
(child_stdin, child_stdout) = (p.stdin, p.stdout)
child_stdin.write('Yoram Opposum\n')
child_stdin.flush()
child_stdout.readlines()
Java 等价物是什么?
我已经试过了
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader inp = new BufferedReader( new InputStreamReader(p.getInputStream()) );
BufferedWriter out = new BufferedWriter( new OutputStreamWriter(p.getOutputStream()) );
out.write( "Some Text!\n\n" );
out.flush();
line = inp.readLine();
print("response1: " + line ); // that's ok
out.write( "Second Line...\n" );
out.flush();
line = inp.readLine();
print("response2: " + line ); // returns an empty string, if it returns,,,
inp.close();
out.close();
顺便说一句,第一次尝试仅适用于 \n\n,但不适用于单个 \n(为什么?)
以下代码有效,但所有输入都是提前给出的,而不是我正在寻找的行为:
out.write( "Aaaaa\nBbbbbb\nCcccc\n" );
out.flush();
line = inp.readLine();
print("response1: " + line );
line = inp.readLine();
print("response2: " + line );
line = inp.readLine();
print("response3: " + line );
line = inp.readLine();
print("response4: " + line );
输出:
response1: AAAAA
response2:
response3: bbbbbb
response4:
正在运行的进程如下所示:
s = sys.stdin.readline()
print s.upper()
s = sys.stdin.readline()
print s.lower()
【问题讨论】:
-
如果您可以为这两个过程提供一个简短但完整的示例,那真的很有帮助。基本上是一种重现行为的方法。