通过stdout在Java和Python之间进行通信

时间:2016-01-19 22:21:48

标签: java python

我有一个通过异步进程调用Python的Java代码,我希望Python进程从Java中侦听stdout直到打印出来。

以下是java代码:

import java.io.*;

public class host {
    public static void main(String[] args) throws Exception{
        System.out.println("java starts at " + System.currentTimeMillis() + " ms");
        ProcessBuilder pb = new ProcessBuilder("python","a.py");
        Process tr = pb.start();
        System.out.println("First msg");
        System.out.println("Second msg");
        Thread.sleep(3000);
        System.out.println("x");
        System.out.println("java ends at " + System.currentTimeMillis() + " ms");
    }
}

以下是python代码:

import sys
import time
if __name__=="__main__":
    fo=open("a.txt","w")
    fo.write('python starts at: %.0f\n'%(time.time()*1000))
    line = sys.stdout.readline()
    while(line != "x\n"):
        fo.write(line+"\n")
        line = sys.stdout.readline()
    fo.write('python ends at: %.0f\n'%(time.time()*1000))
    fo.close()

但是,Python进程似乎无法从Java捕获stdout。由于我不熟悉Java,我不确定是否存在根本错误,以及上述模型是否提供了Java和Python通信之间的有效方法。

编辑(更新)

根据答案/评论,我修改了我的Java代码,如下所示:

import java.io.*;

public class host {
    public static void main(String[] args) throws Exception{
        System.out.println("java starts at " + System.currentTimeMillis() + " ms");
        ProcessBuilder pb = new ProcessBuilder("python","a.py");
        Process tr = pb.start();
        PrintStream ps = new PrintStream(tr.getOutputStream());
        ps.println("First msg"); ps.flush();
        ps.println("Second msg"); ps.flush();
        Thread.sleep(3000);
        ps.println("x"); ps.flush();
        System.out.println("java ends at " + System.currentTimeMillis() + " ms");
    }
}

并更改了python脚本如下:

import sys
import time
if __name__=="__main__":
    fo=open("a.txt","w")
    fo.write('python starts at: %.0f\n'%(time.time()*1000))
    line = sys.stdin.readline()
    while(line != "x\n"):
        fo.write(line+"\n")
        line = sys.stdin.readline()
    fo.write('python ends at: %.0f\n'%(time.time()*1000))
    fo.close()

以下是输出:

python starts at: 1453263858103
First msg

First msg

Second msg

python ends at: 1453263863103

2 个答案:

答案 0 :(得分:2)

接收过程应该监听stdin,而不是stdout。

然后将java的输出传递给python:

java -jar myjava.jar | python mylistener

答案 1 :(得分:1)

在java中,写入您创建的进程:

ProcessBuilder pb = new ProcessBuilder("python","a.py");
Process tr = pb.start();
tr.getOutputStream().println("First msg");

在python中,请阅读stdin

line = sys.stdin.readline()