java:如何读取和写入&从流程到管道(stdin / stdout) [英] java: how to both read and write to & from process thru pipe (stdin/stdout)

查看:164
本文介绍了java:如何读取和写入&从流程到管道(stdin / stdout)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(我是java的新手)
我需要启动一个进程并接收2或3个句柄:对于STDIN,STDOUT,(和STDERR),所以我可以向进程写入输入并接收其输出,与Python中的命令行管道行为相同(例如grep)

(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 (e.g. "grep")

这是通过以下代码实现的:

in Python this is acheived with the following code:

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等价物?

What's the Java equivalent??

我到目前为止尝试过

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第一次尝试仅适用于\ n\ n,但不适用于单身\ n(为什么?)

BTW the first try works only with \n\n, but doesn't work with single \n (why?)

以下代码有效,但所有输入都是事先给出的,而不是我正在寻找的行为:

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

输出:

response1: AAAAA
response2: 
response3: bbbbbb
response4: 

正在运行的过程如下:

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


推荐答案

好吧,这也是我的python代码错误,但与@ Jon的答案相反,有一个EXTRA换行符(确切地说是0xA0,这不是Windows'标准)。

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

一旦我从Java中获取额外的0xA0,python就会添加一个正常\ n到Java在回来的路上,事情顺利进行。

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代码:

for the completeness of the question and answer, here's a working Java code:

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

这是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()

这篇关于java:如何读取和写入&从流程到管道(stdin / stdout)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆