简体   繁体   中英

Runtime.getRuntime().exec() won't work in Java Eclipse

I am running a python script located in my Eclipse project folder with the following Java code:

Process p = Runtime.getRuntime().exec("python pythonscript.pyw");
p.waitFor();
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
System.out.println(in.readLine());

My console always reads null and my p.exitValue() is 2. However, typing the following in Windows command prompt works just fine and I get the correct output:

C:\users\user\workspace\project>python pythonscript.pyw

Does this have something to do with specifying my directory in Eclipse?

You can run such command:

String scriptDir = "./some dir";
Process p = Runtime.getRuntime().exec("cmd /c \"cd " + scriptDir + " && python pythonscript.pyw\"");

Thanks to @aioobe for the link! After checking ProcessBuilder.environment() I realized that Python wasn't in there (even though it's in my PATH system environment variable, weird huh?) So I included the absolute path to my pythonw.exe and it worked just fine :) This is my edited code:

Process p = Runtime.getRuntime().exec("C:/python34/pythonw.exe pythonscript.pyw");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM