3

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);
1
  • Could the python script run under jython? If so call it from java and run in a thread Commented Dec 13, 2012 at 13:46

2 Answers 2

3

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();
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

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.