简体   繁体   English

从Java到python的一个标准输出到一个标准输入

[英]one stdout to one stdin from java to python

I am having this java code 我有这个java代码

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. 从根本上说,它能够打印出从stdout到stdin从java到python的四行代码。 However, when stdout has finished, i would like it to be blocking instead of running again. 但是,当stdout完成时,我希望它被阻止而不是再次运行。

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? 我的第二个问题是,是否将system.out.println都通过管道传递到stdout缓冲区,并且stdin读取它们还是逐行读取它们?

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. 看看EOFError看看为什么会发生这种情况。

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. 在等待其他行的同时,您已经看到了第一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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