Python on Jar-在Java中进程结束后运行python脚本

时间:2019-02-19 04:37:57

标签: java python python-3.x processbuilder runtime.exec

我想在RPi的相机模块使用jar文件捕获照片后运行python脚本(tensorflow的图像标签脚本)。我已经尝试了Runtime和ProcessBuilder,但都没有找到文件或目录。

这是我的运行时代码:

    Process rt = Runtime.getRuntime().exec("python3 -m scripts.image-label.py");
    rt.waitFor();
    BufferedReader in = new BufferedReader(new InputStreamReader(rt.getInputStream()));
    String read = in.readLine();
    ML = read;
    result resfin = new result();
    resfin.setVisible(true);

这是我的ProcessBuilder的代码:

    ProcessBuilder builder = new ProcessBuilder("/home/pi/Desktop/ML/scripts/image-label.py");
    Process np = builder.start();
    np.waitFor();
    BufferedReader in = new BufferedReader(new InputStreamReader(np.getInputStream()));
    String read = in.readLine();
    ML = read;
    result resfin = new result();
    resfin.setVisible(true);

我做错什么了吗?还是我错过了什么?任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

我尝试使用以下代码,尽管我没有尝试使用-m“ module”标志,但仍能正常工作,因为我不知道如何在python中创建模块文件。
发现了一些与代码有关的问题:
1.您需要将python3作为参数传递给流程生成器,如下所示
2.提供python文件的绝对路径。
3.您可以使用Runtime或ProcessBuilder,而不会出现问题。

//        Process rt = Runtime.getRuntime().exec("python3 -m /Users/<user-name>/demo/JavaNotepad/src/main/java/com/mypython.py");
        ProcessBuilder builder = new ProcessBuilder("python3", "-m", "/Users/<user-name>/demo/JavaNotepad/src/main/java/com/mypython.py");
        Process rt = builder.start();
        int exitCode = rt.waitFor();
        System.out.println("Process exited with : " + exitCode);
        BufferedReader in = new BufferedReader(new InputStreamReader(rt.getInputStream()));
        BufferedReader err = new BufferedReader(new InputStreamReader(rt.getErrorStream()));

    System.out.println("Python file output:");
    String line;
    BufferedReader reader;
    if (exitCode != 0) {
        reader = err;
    } else {
        reader = in;
    }
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }