Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling python script from Java using runtime.getruntime.exec

I have a java web development project, and want to call a python script to run in the background and then carry on with the java.

String command = "cmd.exe /c cd "C:\\path\\to\\py\\" && python script.py";
Process p = Runtime.getRuntime().exec(command);

Nothing seems to happen when i call this, but i need to change directory first as the script accesses files in its directory.

Thanks for your help

Edit:

Correct answer was adding start, this is my edited code

String command = "cmd.exe /c cd "C:\\path\\to\\py\\" && start python script.py";
Process p = Runtime.getRuntime().exec(command);
like image 843
FredoAF Avatar asked Mar 23 '26 01:03

FredoAF


2 Answers

Rather than using cmd to change the directory, you can set a process's working directory from the Java side. For example

ProcessBuilder pb = new ProcessBuilder("python", "script.py");
pb.directory(new File("C:\\path\\to\\py"));
Process p = pb.start();
like image 150
Ian Roberts Avatar answered Mar 24 '26 16:03

Ian Roberts


Did you configure your environment to support "executable" python scripts?
If not, you should call it like this:

String command = "cmd.exe /c start python path\to\script\script.py";
Process p = Runtime.getRuntime().exec(command);

The start command runs the appropriate executable (in this case python interpreter), with its supplied arguments (in this case the script itself).

like image 33
Less Avatar answered Mar 24 '26 15:03

Less



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!