1

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

aceminer
  • 4,089
  • 9
  • 56
  • 104
  • 2
    What is your problem? – Malik Brahimi Mar 03 '15 at 02:27
  • @MalikBrahimi The code does not do a print p.stdout.read() Maybe i should modify to show it better – aceminer Mar 03 '15 at 02:29
  • 1
    This might help: http://stackoverflow.com/questions/163542/python-how-do-i-pass-a-string-into-subprocess-popen-using-the-stdin-argument Basically, use p.communicate() instead of p.stdin.write. – matiasg Mar 03 '15 at 02:55

1 Answers1

2

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
7stud
  • 46,922
  • 14
  • 101
  • 127