Reputation: 1301
I'm basically trying to run a Python script using a Java program.
This is a snippet of my Java code:
String cmd = "python /home/k/Desktop/cc.py";
InputStream is = Runtime.getRuntime().exec(cmd).getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader buff = new BufferedReader (isr);
String line;
while((line = buff.readLine()) != null)
System.out.println(line);
This code prints out the output that I want when I run it. But then I modified my cc.py file to take in a sys.argv argument by adding a extra line: print sys.argv[1]
Now when I change my Java String cmd to:
String[] cmd = new String[] {"python /home/k/Desktop/cc.py", "3"};
I get the error:
Exception in thread "main" java.io.IOException: Cannot run program "python /home/k/Desktop/cc.py": error=2, No such file or directory
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1041)
at java.lang.Runtime.exec(Runtime.java:617)
at java.lang.Runtime.exec(Runtime.java:485)
at test.main(test.java:36)
Caused by: java.io.IOException: error=2, No such file or directory
at java.lang.UNIXProcess.forkAndExec(Native Method)
at java.lang.UNIXProcess.<init>(UNIXProcess.java:135)
at java.lang.ProcessImpl.start(ProcessImpl.java:130)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1022)
... 3 more
Why does this not work for an array string, for me? After doing some googling, this works for others.
Upvotes: 0
Views: 2941
Reputation: 69082
Try changing
String[] cmd = new String[] {"python /home/k/Desktop/cc.py", "3"};
to
String[] cmd = new String[] {"python", "/home/k/Desktop/cc.py", "3"};
The first form you use (exec(String command)
) internally tokenizes the given string, if you use the exec(String[] cmdarray)
form, you need to pass the program to execute as first element of the array and the parameters as the other, as no tokenization is applied in that case.
Upvotes: 4