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

3
  • 2
    What is your problem? Commented Mar 3, 2015 at 2:27
  • @MalikBrahimi The code does not do a print p.stdout.read() Maybe i should modify to show it better Commented Mar 3, 2015 at 2:29
  • 1
    This might help: stackoverflow.com/questions/163542/… Basically, use p.communicate() instead of p.stdin.write. Commented Mar 3, 2015 at 2:55

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.