简体   繁体   中英

one stdout to one stdin from java to python

I am having this java code

public static main void (String[] args)
{
    System.out.println("this is iteration 1");
    System.out.println("this is iteration 2");
    System.out.println("this is iteration 3");
    System.out.println("this is iteration 4");
}

Python

import sys 

try:
    while True:
        data = raw_input()
        print "in python " + data
except:
    print error

Desired output

In python : this is iteration 1
In python : this is iteration 2
In python : this is iteration 3
In python : this is iteration 4

Current output

In python : this is iteration 1
In python : this is iteration 2
In python : this is iteration 3
In python : this is iteration 4
Error

Basically what it does is that it was able to print out the four lines from stdout to stdin from java to python. However, when stdout has finished, i would like it to be blocking instead of running again.

My second question would be that, are the system.out.println all piped to the stdout buffer and the stdin reads them or they are read line by line?

My command to run the code is this

java -jar stdOut.jar | python testStdin.py

Almost everything is like you intended it to be. Have a look at EOFError to see why this happens.

import sys 

try:
    while True:
        data = raw_input()
        print "in python " + data
except EOFError:
    pass

So basically you're reading, until the end of the stream is reached. If you want the input to block, the output should stay open as well.

For your second question, just delay the output for a short while somewhere in the middle. You'll already see the first lines, while waiting for the rest of them.

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