3

I want to execute 2 commands in windows operating system(one is batch file and other is python script) using Java Process Builder. But unfortunately not able to do that. I tried many ways.

List<String> commands = new ArrayList<String>();
                commands.add("Testbatch.bat");
                commands.add("Python.exe");
                commands.add("TestPythonScript.py");
                ProcessBuilder probuilder = new ProcessBuilder(commands);
                Process process = probuilder.start();

Here it is executing Batch file but Not the python. Here Process builder is Treating the Commands as arguments except the first command. Also tried below approach but no luck.

String [] commands={"CMD","/C","Testbatch.bat","Python.exe","TestPythonScript.py"};
ProcessBuilder probuilder = new ProcessBuilder(commands);
Process process = probuilder.start();

Nothing worked for me to execute commands in sequence(one after other) by using ProcessBuilder, I almost spent 3 days but not able to find the correct approach. Can any one please suggest me the approach to achieve the same.

Thanks,

Sudheer

1 Answer 1

6

ProcessBuilder will only do one command at a time -- as you're discovering, when you pass it an array of Strings, only the first String is taken as a command, the rest are used as arguments.

To do more than one command, you'll need to create a new ProcessBuilder for each.

To make sure multiple commands run in sequence, you'll have to make sure one command finishes before you start the next, otherwise the order of execution will be uncertain.

The way you do this is to take the Process object returned by ProcessBuilder.start() and use its waitFor() method to wait for each command to complete.

Sign up to request clarification or add additional context in comments.

2 Comments

Sudheer, if kshetline's answer helped you with your problem, please be sure to accept their answer.
@Kshetline's Thank you very much!! good explanation , Your answer resolved my problem .

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.