简体   繁体   English

java:如何通过管道读取和写入进程(stdin / stdout)

[英]java: how to both read and write to & from process thru pipe (stdin/stdout)

(i'm new to java) I need to start a process and receive 2 or 3 handles: for STDIN, STDOUT, (and STDERR), so I can write input to the process and receive its output, the same way command line pipes behave (eg "grep") (我是java新手)我需要启动一个进程并接收2个或3个句柄:对于STDIN,STDOUT,(和STDERR),所以我可以向进程写入输入并接收其输出,命令行管道的方式相同表现(例如“grep”)

in Python this is acheived with the following code: 在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()

What's the Java equivalent?? 什么是Java等价物?

I've tried so far 到目前为止我已经尝试过了

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();

BTW the first try works only with \\n\\n, but doesn't work with single \\n (why?) BTW第一次尝试仅适用于\\ n \\ n,但不适用于单\\ n(为什么?)

the following code works, but all input is given in advance, not the behavior i'm looking for: 以下代码有效,但所有输入都是事先给出的,而不是我正在寻找的行为:

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 );

output: 输出:

response1: AAAAA
response2: 
response3: bbbbbb
response4: 

the process being run looks like that: 正在运行的进程看起来像这样:

s = sys.stdin.readline()
print s.upper()
s = sys.stdin.readline()
print s.lower()

ok, it was also my python's code fault, but opposite to @Jon's answer, there was an EXTRA newline (0xA0 to be exact, which isn't Windows' standard). 好吧,这也是我的python的代码错误,但与@ Jon的答案相反,有一个EXTRA换行符(确切地说是0xA0,这不是Windows的标准)。

once i'm strip()ing the extra 0xA0 from the line i get from Java, python adds a single "normal" \\n to Java on the way back, and things run smoothly. 一旦我从Java中获取了额外的0xA0,python就会在回来的路上为Java添加一个“正常”的\\ n,并且事情顺利进行。

for the completeness of the question and answer, here's a working Java code: 为了问题和答案的完整性,这是一个有效的Java代码:

import java.io.*;
import java.util.*;

public class Main {

    public static BufferedReader inp;
    public static BufferedWriter out;

    public static void print(String s) {
    System.out.println(s);
    }

    public static String pipe(String msg) {
    String ret;

    try {
        out.write( msg + "\n" );
        out.flush();
        ret = inp.readLine();
        return ret;
    }
    catch (Exception err) {

    }
    return "";
    }



    public static void main(String[] args) {

    String s;
    String cmd = "c:\\programs\\python\\python.exe d:\\a.py";

    try {

        print(cmd);
        print(System.getProperty("user.dir"));
        Process p = Runtime.getRuntime().exec(cmd);

        inp = new BufferedReader( new InputStreamReader(p.getInputStream()) );
        out = new BufferedWriter( new OutputStreamWriter(p.getOutputStream()) );

        print( pipe("AAAaaa") );
        print( pipe("RoteM") );

        pipe("quit")
        inp.close();
        out.close();
    }

    catch (Exception err) {
        err.printStackTrace();
    }
    }
}

and this is the python code 这是python代码

import sys
s = sys.stdin.readline().strip()
while s not in ['break', 'quit']:
    sys.stdout.write(s.upper() + '\n')
    sys.stdout.flush()
    s = sys.stdin.readline().strip()

I believe the problem is in the process you're calling: 我相信问题出在你正在调用的过程中:

s = sys.stdin.readline()
print s.upper()
s = sys.stdin.readline()
print s.lower()

I suspect that readline is going to read the line but s will not include the line terminator. 我怀疑readline将读取该行,但s包括行终止符。 You're then printing that line, but without a line terminator ... Java is then blocking until it reads a line terminator, which will block forever as the process isn't giving one. 然后你打印那行,但是没有行终止符 ......然后Java会阻塞,直到它读取一个行终止符,它将永远阻塞,因为进程没有给出。

This is all a bit of a guess as it's not exactly clear to me what language your called process is in - if print actually does output a line terminator, then it's an incorrect guess. 这是一个猜测,因为我不清楚你所调用的语言是什么语言 - 如果print 确实输出了行终止符,那么这是一个不正确的猜测。 However, if not, you may need to change it to something like: 但是,如果没有,您可能需要将其更改为:

s = sys.stdin.readline()
println s.upper()
s = sys.stdin.readline()
println s.lower()

EDIT: That doesn't explain the blank lines in sample output... no idea what's going on, really, but unfortunately I can't look into it now. 编辑:这并没有解释样本输出中的空白行...不知道发生了什么,真的,但不幸的是我现在无法调查。

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

相关问题 测试从标准输入读取并写入标准输出的 Java 程序 - Test java programs that read from stdin and write to stdout 从StdIn读取并同时写入StdOut是否安全? - Is it safe to read from StdIn and write to StdOut concurrently? 从Java Process调用jpegoptim和pngquant,在stdin中传递图像,并在stdout中读取结果:管道破裂或挂起 - Calling jpegoptim and pngquant from java Process, passing image in stdin and reading result in stdout: broken pipe or hang 从外部进程的stdin / stderr / stdout读取和写入的正确位置,应在超时内终止 - Correct place to read and write from stdin/stderr/stdout of external process which should be terminated within timeout AIR 1.5应用程序是否可以从stdin读取并写入stdout / stderr? - Is there a way for an AIR 1.5 app to read from stdin and write stdout/stderr? 从python到stdin java的stdout - stdout from python to stdin java 在Java 6中使用继承的stdin / stdout / stderr启动进程 - Starting a process with inherited stdin/stdout/stderr in Java 6 Java:同时使用进程的stdin / stdout - java: work with stdin/stdout of process in same time 损坏的 Pipe Java 程序写入外部 C 程序 stdin 和从 stdout 读取 - Broken Pipe Java program writing in an external C programs stdin and reading from stdout 如何在Java中读取/写入进程 - How to Read/Write to a Process in Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM