Why is my runtime command ignored after calling a batch file?

Viewed 46
public class Test_Python 
{
    public static void main( String[] args ) throws IOException
    {
        
        String command = "cmd /k start cmd.exe /k \"cd C:\\Workspace\\supply\\environment\\ &&  setup.bat &&  python -V ";
       Runtime.getRuntime().exec(command);
    }
}

When I execute my code, the "python -V" does not work, it is not executed in the cmd window.

But if I delete the "setup.bat" from my command, the "python -V" is executed (I can read the version in the cmd window)

Also, if I manually start a cmd, type setup.bat and then python -V it works.

My batch file is used to set my working environment:

SET basedir=%~dp0
echo %basedir%

cmd /k "cd %basedir%\..\scripts && set PYTHONPATH=%basedir%\..\lib"

Is there any way to know why it fails?

1 Answers

Unlike python Java may need some help. As I can see you are running on Windows.

You invoke the Runtime.exec() method. The method returns a Process instance, and in it's documentation you can read

By default, the created process does not have its own terminal or console. All its standard I/O (i.e. stdin, stdout, stderr) operations will be redirected to the parent process, where they can be accessed via the streams obtained using the methods getOutputStream(), getInputStream(), and getErrorStream(). The parent process uses these streams to feed input to and get output from the process. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the process may cause the process to block, or even deadlock.

So it is likely your process is started by the OS but gets blocked due to I/O restrictions. Get around that by reading the STDOUT and STDERR streams until your process finishes. One good programming model is visible at https://www.baeldung.com/run-shell-command-in-java

Now that we know the OS is not blocking the process, the issue may be inside the command itself. Note you concatenated several commands using the && operator. I do not have a windows system but searched a bit online:

https://www.ionos.com/digitalguide/server/know-how/windows-cmd-commands/ CommandA && CommandB (the second command is only run if the first was successful)

To check how the first part of your command exits run it separately in Java and do not forget to print the process.exitValue() method.

But looking at the whole picture, all you do with the first part is to change the working directory and set some environment variable. What stops you from running the ProcessBuilder methods? The example in the documentation directly sets the environment and directory.

Related