简体   繁体   中英

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);

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();

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM