0

Here's what I'm looking at, a python script uses subprocess.run (or call, or popen, it doesn't seem to matter) to run a simple windows batch script, the batch file returns a non-zero exit code, but python thinks the return code was zero.

Here's the simple repro I have right now:

Batch script (error.bat):

@echo off

if "%1" == "a" (
    exit /b 1
    goto end
)

:end

Python script:

import subprocess

retcode = subprocess.run(['error.bat', 'a'])

print(retcode)

Running the batch file from the command line results in %errorlevel% being set to 1. But running the python script the return code comes back as 0:

CompletedProcess(args=['error.bat', 'a'], returncode=0)

For a simpler script this works fine, but somehow something about the if statement and the goto results in python losing the return code. Is there something I'm missing here? Is this a python bug (I'm using 3.6)?

Wedge
  • 19,513
  • 7
  • 48
  • 71
  • 1
    From the other issue, a workaround is to use `call`, e.g. `subprocess.run('call error.bat a', shell=True)`. Also, in general do not use an args list when running a batch script. `subprocess.list2cmdline` doesn't support command-line quoting for the CMD shell (as if anything could; it's such a mess). – Eryk Sun Jul 09 '19 at 23:45
  • I'd suggest that the point is that the process `error.bat` itself completes successfully; `https://docs.python.org/3/library/subprocess.html` tells me that perhaps the `check` flag setting may point the path to success. – Magoo Jul 09 '19 at 23:51
  • 1
    @Magoo, it's intended for error.bat to exit with an error, but `exit /b` only exits the batch script with an errorlevel; it doesn't exit the shell process with an exit code. The way CMD evaluates expressions means that sometimes the errorlevel propagates to the process exit code, and sometimes not. The details are discussed in answers to the linked question. As mentioned above, a workaround is to run the script via `call`, which ensures the errorlevel propagates to the exit code. – Eryk Sun Jul 10 '19 at 03:31

0 Answers0