如果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,我覺得它要容易得多,儘管需要更多的代碼來使用。
絕對路徑到您的.py文件將我會嘗試的第一件事。 –