使用input()将Java程序的输出发送到Python进程

2024-09-30 02:26:14 发布

您现在位置:Python中文网/ 问答频道 /正文

谢谢你的帮助 我正在尝试从Java进程到Python进程写入和读取字符。 另一种方法(从python打印并在Java进程中获取)运行良好,但python进程似乎无法获取Java进程的输出。你知道吗

以下是我尝试使用的代码:

爪哇

管理python进程的类

class Pyexe {
Process pypr;
BufferedReader pybuffreader;
BufferedWriter pybuffwriter;
public Pyexe(String filecmd) throws IOException{
    pypr=Runtime.getRuntime().exec("py "+filecmd);
    pybuffreader=new BufferedReader(new InputStreamReader(pypr.getInputStream()));
    pybuffwriter=new BufferedWriter(new OutputStreamWriter(pypr.getOutputStream()));

}
public void Pyend(){
    this.pypr.destroy();
}

}

Main:启动python进程,发送一个字符串,然后获取python输出

public class JavaLearn{
public static void main(String[]argv)throws IOException{

    Pyexe pyexe=new Pyexe("c:/pathtofile/testpy.py");
    pyexe.pybuffwriter.write("Have a nice day\n");
    String line=pyexe.pybuffreader.readLine();
    System.out.println(line);}


    }

Python 一个简单的脚本:get input(),以小写形式打印

line=input()
print(line.lower())

当启动时,python进程只是不确定地等待输入。 如果我只使用:

print("Something".lower())

使用Bufferedreader,Java进程从Python获取输出。你知道吗

你知道怎么回事吗? 先谢谢你


Tags: newstring进程linejavapublicclasspypr

热门问题