簡體   English   中英

從 Java 運行 Python 腳本

[英]Run Python script from Java

我正在嘗試在 Java 中運行.py腳本,但是當我運行 Java 代碼時,它沒有顯示任何輸出。 我做錯了什么? 我試過:

ArrayList<String> command = new ArrayList<String>();
    //xterm will be launched, if platform is Linux.
    command.add("xterm");
    command.add("-c");
    command.add("python");
    command.add("/home/clef/Escritorio/use_archive.py");
    command.add("/home/clef/classification/STOP_WORDS.tar.gz");
    command.add("/home/clef/Escritorio/Prueba_linea/000006/6.jpg");
    command.add(" > ~/Escritorio/mike.txt");
    //command.add("--revert");    // switch to revert the patch

    ProcessBuilder pb = new ProcessBuilder(command);

    Process p = null;

    if (pb != null) {

        try {
            p = pb.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (p != null) {
            try {
                p.waitFor();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

    String line = "";
    ArrayList<String> allOut = new ArrayList<>();
    System.out.println("salida");
    try
    {
        System.out.println("SALIDA-----------:");
        while ((line = reader.readLine())!= null)
        {
            System.out.println(line);
            allOut.add(line);
        }
    } catch (IOException ex)
    {
        //allOut = "0";
        //Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        //System.out.println("erro3");        }
        System.out.println("error");
    }

該腳本來自 NVIDIA DIGITS 框架,但我無法從 Java 運行任何 python 腳本。 如果我在終端中運行.py腳本,我會得到輸出:

Unknown file: solver.prototxt
    Unknown file: train_val.prototxt
    Processed 1/1 images in 0.076470 seconds ...
    -------- Prediction for /home/clef/Escritorio/Prueba_linea/000006/6.jpg --------
     51.4607% - "0"
      7.7899% - "1"
      5.7782% - "2"
      5.6086% - "3"
      5.2513% - "4"

    Script took 0.523756 seconds.

嘗試這個:

Process p = Runtime.getRuntime().exec("python yourapp.py");

Exec 運行系統命令,如果您安裝了 python,它將像在操作系統的命令終端中一樣運行 python 文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM