Invalid python exit code when calling windows script

It seems I am not getting the correct exit code from subprocess.call on Windows.

import subprocess
exit_code = subprocess.call(['ant.bat', 'fail'])
print exit_code # prints 0

Doing the same in windows seems to return something other than 0

> echo %errorlevel%
0
> ant fail
> echo %errorlevel%
1

Should the values ​​of both calls give the same value? Am I doing something wrong?

In the worst case, how to check the value of% errorlevel% in my python script?

UPDATE:

I tried something like this to get the error level value:

environment = os.environment.copy()
cmd = subprocess.Popen(['ant.bat', 'fail'], env = environment)
for key, value in environment.items():
    print '%s = %s' % (key, value)

However, I do not see an error in this dictionary (os.getenv ['errorlevel'] also does not work).

+5
source share
3 answers

The process exit code and the errorlevel environment variable do not match:

ant.bat:

if "%1"=="batch_fail" exit /B 1
if "%1"=="proc_fail" exit 1


>>> import subprocess
>>> subprocess.call(['ant.bat', 'batch_fail'])
0
>>> subprocess.call(['ant.bat', 'proc_fail'])
1

batch_fail errorlevel 1, . proc_fail, , 1. , , , ant.bat :

ant_wrapper.bat:

@echo off
call ant.bat %1
if errorlevel 1 exit 1

>>> subprocess.call(['ant_wrapper.bat'])
0
>>> subprocess.call(['ant_wrapper.bat', 'batch_fail'])
1
>>> subprocess.call(['ant_wrapper.bat', 'proc_fail'])
1

Edit:

, Popen. cmd/K, . exit %errorlevel% stdin ():

#test errorlevel==1
>>> p = subprocess.Popen(['cmd', '/K', 'ant.bat', 'batch_fail'], 
      stdin=subprocess.PIPE, stdout=subprocess.PIPE)
>>> stdoutdata, stderrdata = p.communicate(b'exit %errorlevel%\r\n')
>>> p.returncode
1

#test errorlevel==0
>>> p = subprocess.Popen(['cmd', '/K', 'ant.bat'], 
      stdin=subprocess.PIPE, stdout=subprocess.PIPE)
>>> stdoutdata, stderrdata = p.communicate(b'exit %errorlevel%\r\n')
>>> p.returncode
0
+7

, call,

cmd = [os.environ['COMSPEC'], '/c', 'call', bat_file]
try:
    subprocess.check_call(cmd)
except subprocess.CalledProcessError:
    # Error handling code

( subprocess.check_call, subprocess.call ).

if errorlevel 1 exit 1 script, ( bash set -e).

0

os.system('ant.bat fail')does exactly what you want. It returns the error rate.

-1
source

All Articles