Reputation: 61
For a project I need to start python.exe via Runtime.getRuntime.exec(). However, when I try to run it it won't execute, but it doesn't throw up an IOException. Here's the code:
try
{
Process process=Runtime.getRuntime().exec("C:\\Program Files (x86)\\PythonTest\\python.exe");
}
catch (IOException e)
{
System.out.println("Cannot find python.exe");
e.printStackTrace();
}
Upvotes: 0
Views: 1503
Reputation: 719299
I think that the problem is due to eval
incorrectly splitting the command string. My understanding is that exec("C:\\Program Files (x86)\\PythonTest\\python.exe")
will attempt to run an application called "C:\\Program"
, passing it 2 command line arguments.
Try this instead:
exec(new String[]{"C:\\Program Files (x86)\\PythonTest\\python.exe"});
The exec(String, ...)
command line parsing is primitive, and often has the incorrect behaviour from the programmer's perspective. The best bet is often to split the command and arguments yourself.
Upvotes: 1
Reputation: 201497
You need to get the output from the process and (waitFor()
it to finish). Something like,
final String cmd = "C:/Program Files (x86)/PythonTest/python.exe";
Process p = Runtime.getRuntime().exec(cmd);
final InputStream is = p.getInputStream();
Thread t = new Thread(new Runnable() {
public void run() {
InputStreamReader isr = new InputStreamReader(is);
int ch;
try {
while ((ch = isr.read()) != -1) {
System.out.print((char) ch);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
p.waitFor();
t.join();
To actually do something with python
you'll want to get the OutputStream
.
Upvotes: 1