1

Consider the following String command:

C:\TS\Veit\Test\python\Python-3.6.9\python.exe -m pip install -r C:\TS\Veit\Test\python\packages\requirements.txt  --find-links --no-index > C:\TS\Veit\Test\python\logs\python.log 2>&1

This command install python and its packages based on the requirements file requirements.txt, and then put the output of the command (both stdout and stderr) in a file called python.log.

When I run this command on Windows from the command line, it works perfectly, and I have my python.log file created with all the logs. However, when I run it from java, the command doesn't create the python.log file.

Two ways I have tried so far:

1. Using Runtime exec:

    Runtime.getRuntime().exec(script_WINDOWS);

With script_windows equals to: pythonInterpreter+" -m pip install -r "+requirementsFilePath+" --find-links "+pathToPackages+" --no-index > "+ pythonLogFileLocation +File.separator+"python.log 2>&1" Which is exactly the same command I put above.

With this method, Runtime does install python for me but I have no python.log file created.

2. Using ProcessBuilder:

    ProcessBuilder builder = new ProcessBuilder(script_WINDOWS);
    builder.redirectErrorStream(true);
    Process p = builder.start();
    BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line;
    while (true) {
        line = r.readLine();
        if (line == null) { break; }
        FileUtils.writeStringToFile(FileUtils.getFile(pythonLogFileLocation+"python.log"), line, "UTF-8");
        FileUtils.writeStringToFile(FileUtils.getFile(pythonLogFileLocation+"python.log"), "\n", "UTF-8");

    }

This method ends in the following error:

java.io.IOException: Cannot run program "C:\TS\Veit\Test\python\Python-3.6.9\python.exe -m pip install -r C:\TS\Veit\Test\python\packages\requirements.txt --find-links C:\TS\Veit\Test\python\packages --no-index > C:\TS\Veit\Test\python\logs\python.log 2>&1": CreateProcess error=2, The system cannot find the file specified

Since the command works perfectly from the command line, I think it's the way I'm trying to execute it from Java that is causing the problem of the python.log file not being created. Any help would be appreciated.

Jesse James
  • 1,203
  • 5
  • 22
  • 39
  • 1
    I suspect your issue is that exec needs to spawn an instance of cmd.exe in order to use output redirection. See https://stackabuse.com/executing-shell-commands-with-java – Deadron Jun 29 '21 at 14:13
  • That was it! Thank you so much! Could you please put your comment as an answer so I can upvote it? – Jesse James Jun 29 '21 at 14:29

1 Answers1

1

I suspect your issue is that exec needs to spawn an instance of cmd.exe in order to use output redirection. See stackabuse.com/executing-shell-commands-with-java

Deadron
  • 5,135
  • 1
  • 16
  • 27