簡體   English   中英

為什么這個python腳本沒有在java中執行

[英]Why this python script isn't executing in java

繼承我的代碼

public void addImg(){
    try{
        //Attempt 1
        Runtime r = Runtime.getRuntime();
        Process p = r.exec("/usr/bin/python2.7 ../wc.py");
        p.waitFor();
        p.destroy();

        //Attempt 2
        p = r.exec("python2.7 ../wc.py");
        p.waitFor();
        p.destroy();
    }catch (Exception e){
        String cause = e.getMessage();
        System.out.print(cause);
    }
}

我一直試圖讓這個工作大約一個小時沒有,似乎沒有任何工作,並沒有顯示錯誤。 我更關心如何調試這個,但是我的代碼有什么問題可以說明為什么這個腳本沒有執行?

如果exec()方法不立即拋出異常,則只表示它可以執行外部進程。 然而, 這並不意味着它成功執行或者甚至沒有正確執行。

有很多方法可以檢查外部進程是否成功執行,下面列出了幾個:

使用Process.getErrorStream()和Process.getInputStream()方法讀取外部進程的輸出。

查看外部進程的退出代碼,代碼0表示正常執行,否則可能發生錯誤。

考慮添加以下代碼以進行調試:

public void addImg(){
    try{
        Runtime r = Runtime.getRuntime();

        //Don't use this one...
        //Process p = r.exec("/usr/bin/python2.7 ../wc.py");
        //p.waitFor();
        //p.destroy();

        //Use absolute paths (e.g blahblah/foo/bar/wc.py)
        p = r.exec("python2.7 ../wc.py");

        //Set up two threads to read on the output of the external process.
        Thread stdout = new Thread(new StreamReader(p.getInputStream()));
        Thread stderr = new Thread(new StreamReader(p.getErrorStream()));

        stdout.start();
        stderr.start();

        int exitval = p.waitFor();
        p.destroy();

        //Prints exit code to screen.
        System.out.println("Process ended with exit code:" + exitval);
    }catch(Exception e){
        String cause = e.getMessage();
        System.out.print(cause);
    }
}

private class StreamReader implements Runnable{
    private InputStream stream;
    private boolean run;

    public StreamReader(Inputstream i){
        stream = i;
        run = true;
    }

    public void run(){
        BufferedReader reader;
        try{
            reader = new BufferedReader(new InputStreamReader(stream));

            String line;

            while(run && line != null){
                System.out.println(line);
            }
        }catch(IOException ex){
            //Handle if you want...
        }finally{
            try{
                reader.close();
            }catch(Exception e){}
        }
    }
}

此外,嘗試在調用外部應用程序時使用ProcessBuilder,盡管需要更多代碼,但我發現它更容易使用。

您需要查看通過運行命令返回的結果,而不僅僅是捕獲異常。

查看exitValue()和方法以獲取Process對象上的輸出和錯誤流。

我的猜測是python無法找到你的程序,因為../由你的shell解決,使用exec啟動的程序不是從shell運行的。

打印錯誤流:

Runtime r = Runtime.getRuntime();
String line;
Process p = r.exec("/usr/bin/python2.7 ../wc.py");
InputStream stdin = p.getErrorStream();
InputStreamReader isr = new InputStreamReader(stdin);
BufferedReader br = new BufferedReader(isr);
p.waitFor();
while ( (line = br.readLine()) != null)
    System.out.println("-"+line);
p.destroy();

可能找不到wc.py。

暫無
暫無

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

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