user3853393
user3853393

Reputation: 253

How to execute commands in sequence using Processbuilder

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

Upvotes: 3

Views: 4149

Answers (1)

kshetline
kshetline

Reputation: 13682

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.

Upvotes: 6

Related Questions