问题
import java.io.*;
class RunTest {
public static void main(String a[]) {
try {
String prg = "import sys\nprint int(sys.argv[1])+int(sys.argv[2])\n";
BufferedWriter out = new BufferedWriter(new FileWriter("test1.py"));
out.write(prg);
int number1 = 1;
int number2 = 2;
ProcessBuilder pb = new ProcessBuilder("python","test1.py",""+number1,""+number2);
Process p = pb.start();
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
int ret = new Integer(in.readLine()).intValue();
System.out.println("value is : "+ret);
} catch(Exception e) {
e.printStackTrace();
}
}
}
When I run this code (I'm using Eclipse), I get the stack trace:
java.io.IOException: Cannot run program "python": CreateProcess error=2, The system cannot find the file specified at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048) at RunTest.main(RunTest.java:11) Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified at java.lang.ProcessImpl.create(Native Method) at java.lang.ProcessImpl.(ProcessImpl.java:386) at java.lang.ProcessImpl.start(ProcessImpl.java:137) at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029) ... 1 more
Anyone have any idea why and what I can do?
Thanks!
回答1:
You have to flush()
and you should close()
(which will also flush()
) after you write to the File
.
out.write(prg);
out.close(); // <-- add this.
Also, you'll need to add python
to your PATH.
回答2:
Sorry, this is probably really unhelpful, but somehow, it just started working. No idea why or how, because I haven't changed anything. Eclipse basically just restarted itself randomly and now it works! Sorry I couldn't post a solution that will help others, but thanks anyway for your help @MadProgrammer and @Elliott !
来源:https://stackoverflow.com/questions/28204342/java-processbuilder-cannot-find-file-specified