使用ProcessBuilder执行简单的Python脚本

时间:2018-02-23 12:18:37

标签: java python netbeans bufferedreader processbuilder

我尝试使用ProcessBuilder从CMD执行一个简单的python脚本,该脚本打印到命令行,然后将该文本读入Java并通过netbeans中的System.out.println()输出。我的问题是BufferedReader似乎暂停在.readLine()然后在py脚本停止运行后批量输出文本,而不是输出实时。

我的流程如下:

[执行python脚本]

Executors.newSingleThreadExecutor().execute(this::TEST);

[运行执行]

public void TEST(){
    try {
        ProcessBuilder py = new ProcessBuilder("cmd", "/C", "C:\\Users\\Documents\\TEST.py");
        String readLine;
        Process launch = py.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(launch.getInputStream()));
        while((readLine = reader.readLine()) != null){
            System.out.println(readLine);
        }
    } catch (IOException ex) {Logger.getLogger(Template.class.getName()).log(Level.SEVERE, null, ex);}
}

[这是我希望运行并阅读现场的python脚本]

import Tkinter, tkFileDialog, tkMessageBox


root = Tkinter.Tk()
root.withdraw()
root.resizable(width=Tkinter.TRUE, height=Tkinter.TRUE)
root.geometry('{}x{}'.format(400,600))

print("hello1\n")
print("hello2\n")
print("hello3\n")
print("hello4\n")
print("hello5\n")
tkMessageBox.showinfo("Complete!", "testing")
print("hello6\n")
print("hello7\n")
print("hello8\n")
print("hello9\n")
print("hello10\n")
tkMessageBox.showinfo("Complete!", "testing")

感谢!!!

2 个答案:

答案 0 :(得分:0)

第一:你的命令什么也没做。它是cmd /C C:\Users\Documents\TEST.py,除了告诉您C:\Users\Documents\TEST.py不是命令之外什么都不做。您需要致电cmd /C start C:\Users\Documents\TEST.py才能执行某些操作。

仍然这不会使你的代码工作。这里的问题是你在那里调用一个cmd来启动一个python进程。当您现在获取输入流时,您将获得不是您要查找的cmd输入流。

为了让它工作,通过调用python C:\Users\Documents\TEST.py直接调用python。确保python在PATH中,以便工作。

您的代码应该如下所示:

try
{
    ProcessBuilder py = new ProcessBuilder("python", "C:\\Users\\Documents\\TEST.py");
    String readLine;
    Process launch = py.start();
    BufferedReader reader = new BufferedReader(new InputStreamReader(launch.getInputStream()));
    while ((readLine = reader.readLine()) != null)
    {
        System.out.println(readLine);
    }
}
catch (IOException ex)
{
    Logger.getLogger(Template.class.getName()).log(Level.SEVERE, null, ex);
}

这可以为您提供所需的结果。

答案 1 :(得分:0)

一个常见的问题可能是你没有刷新你的 python 标准。我建议添加

import sys

# your code here...

sys.stdout.flush()

到您的代码以刷新您的 python 输出。