标准输出从 python 到标准输入 java

stdout from python to stdin java

我有一个从 python 到 java 中的标准输入的标准输出。

我正在使用

Python代码

p = subprocess.Popen(command, stdout = subprocess.PIPE, stdin = subprocess.PIPE)
p.stdin.write("haha")
print "i am done" #it will never hit here

Java代码

Scanner in = new Scanner(System.in)
data = in.next()// the code blocks here

基本上发生的事情是 子进程运行 jar 文件 ---> 它阻塞,因为标准输入仍然阻塞,因为它没有显示任何内容

python:

p.stdin.write("haha")

java:

Scanner in = new Scanner(System.in)
data = in.next()

来自Java Scanner docs

By default, a scanner uses white space to separate tokens. (White space characters include blanks, tabs, and line terminators.

您的 python 代码不会写入扫描程序识别为 令牌结尾的任何内容,因此扫描程序会坐在那里等待读取更多数据。换句话说,next() 读取输入直到遇到空白字符,然后 returns 读入数据,减去终止空白。

这个python代码:

import subprocess

p = subprocess.Popen(
    [
        'java',  
        '-cp',
        '/Users/7stud/java_programs/myjar.jar',
        'MyProg'
    ],
    stdout = subprocess.PIPE, 
    stdin = subprocess.PIPE,
)


p.stdin.write("haha\n")
print "i am done" 
print p.stdout.readline().rstrip()

...使用此 java 代码:

public class MyProg {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String data = in.next();

        System.out.println("Java program received: " + data);
    }
}

...产生此输出:

i am done
Java program received: haha