简体   繁体   中英

stdout from python to stdin java

I have having a stdout from python to stdin in java.

I am using

Python code

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

Java code

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

Basically what happens is the subprocess runs the jar file ---> it blocks as the stdin is still blocking since it shows no content

python:

 p.stdin.write("haha") 

java:

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

From the Java Scanner docs :

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

Your python code does not write anything that a Scanner recognizes as the end of a token , so the Scanner sits there waiting to read more data. In other words, next() reads input until it encounters a whitespace character, then it returns the data read in, minus the terminating whitespace.

This python code:

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

...with this java code:

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

...produces this output:

i am done
Java program received: haha

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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