0

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.

Beryllium
13k11 gold badges59 silver badges88 bronze badges
asked Oct 1, 2013 at 16:59
1
  • If you send as cmd[0]=python path is like sending 'python path'. If you pass the raw String instead of array, the exec will parse it and assume you are sending arguments split by the space, and if you needed spaces you have to use quotes. Commented Oct 1, 2013 at 17:16

1 Answer 1

4

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.

answered Oct 1, 2013 at 17:06
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that worked. But, could you elaborate why String cmd = "python /home/k/Desktop/cc.py"; worked before without using an array?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.