Call Python From Bat File And Get Return Code
The windows shell saves the return code in the ERRORLEVEL
variable:
python somescript.pyecho %ERRORLEVEL%
In the python script you can exit the script and set the return value by calling exit()
:
exit(15)
In older versions of python you might first have to import the exit()
function from the sys
module:
from sys import exitexit(15)
You can try this batch script for this:
@echo offREM %1 - This is the parameter we pass with the desired return code for the Python script that will be captured by the ErrorLevel env. variable. REM A value of 0 is the default exit code, meaning it has all gone well. A value greater than 0 implies an errorREM and this value can be captured and used for any error control logic and handling within the script set ERRORLEVEL=set RETURN_CODE=%1echo (Before Python script run) ERRORLEVEL VALUE IS: [ %ERRORLEVEL% ]echo.call python -c "import sys; exit_code = %RETURN_CODE%; print('(Inside python script now) Setting up exit code to ' + str(exit_code)); sys.exit(exit_code)"echo.echo (After Python script run) ERRORLEVEL VALUE IS: [ %ERRORLEVEL% ]echo.
And when you run it a couple of times with different return code values you can see the expected behaviour:
PS C:\Scripts\ScriptTests> & '\TestPythonReturnCodes.cmd' 5(Before Python script run) ERRORLEVEL VALUE IS: [ 0 ](Inside python script now) Setting up exit code to 5(After Python script run) ERRORLEVEL VALUE IS: [ 5 ]PS C:\Scripts\ScriptTests> & '\TestPythonReturnCodes.cmd' 3(Before Python script run) ERRORLEVEL VALUE IS: [ 0 ](Inside python script now) Setting up exit code to 3(After Python script run) ERRORLEVEL VALUE IS: [ 3 ]PS C:\Scripts\ScriptTests