通过Java运行Python脚本?

时间:2015-07-16 18:35:41

标签: java python input terminal

我正在通过java运行python脚本。到目前为止我提供的部分代码在下面提供,成功运行不需要用户输入的python脚本。它正在显示我在python脚本中指示的要在终端中打印的内容。我是通过mac oxs终端这样做的。但是,每当我运行需要用户输入的python脚本时,它都不会在"输入"之后显示任何内容。来自python脚本的语句。 我需要这个来处理来自python脚本的用户输入。

请帮我解决这个问题,谢谢!

public static void main(String[] args) {
    test obj = new test();

    //in mac oxs
    String command = "python testLOL.py";
    String output = obj.executeCommand(command);
    System.out.println(output);     

}

private String executeCommand(String command) {

    StringBuffer output = new StringBuffer();

    Process p;
    try {
        Runtime r = Runtime.getRuntime();
        p = r.exec(command);
        p.waitFor();
        BufferedReader reader = 
        new BufferedReader(new InputStreamReader(p.getInputStream()));

        String line = "";           
        while ((line = reader.readLine()) != null) {
            output.append(line + "\n");
        }

        p.waitFor();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return output.toString();   
}

1 个答案:

答案 0 :(得分:0)

您可以创建两个线程,将两个流绑定到进程

public static void main(final String[] args){
    executeCommand("python test/test.py");
}

private static void executeCommand(final String command){
    final Process p;
    try{
        p = Runtime.getRuntime().exec(command);

        Thread bindIn = new Thread(() -> {
            try{
                int av;
                while(!Thread.interrupted())
                while((av = System.in.available()) > 0){
                    byte[] bytes = new byte[av];
                    System.in.read(bytes);
                    p.getOutputStream().write(bytes);
                    p.getOutputStream().flush();
                }

                System.out.println("bindIn ended");
            }catch(Exception e){
                e.printStackTrace();
                return;
            }
        });

        Thread bindOut = new Thread(() -> {
            try{
                int av;
                while(!Thread.interrupted())
                while((av = p.getInputStream().available()) > 0){
                    byte[] bytes = new byte[av];
                    p.getInputStream().read(bytes);
                    System.out.write(bytes);
                }

                System.out.println("bindOut ended");
            }catch(Exception e){
                e.printStackTrace();
                return;
            }
        });

        bindIn.start();
        bindOut.start();

        p.waitFor();

        bindIn.interrupt();
        bindOut.interrupt();
    }catch(Exception e){
        e.printStackTrace();
    }
}

请注意,现在您不需要在结尾读取输出,因为它是即时传输的。

在您的代码中,您执行了具有自己的流的流程,因此写入System.in并未导致写入p.getOutputStream(),反之亦然。