views:

1795

answers:

2

I'm looking for a way to call a python script from a batch file and getting a return code from the python script. Confusing I know, but it's based on a system that's currently in use. I'd re-write it, but this way would be much, much quicker.

So:

Bat ---------------------> Python
     * call python file *

Bat <--------------------------------- Python
      * python does a load of work *
      * and returns a return code  *
+8  A: 

The windows shell saves the return code in the ERRORLEVEL variable:

python somescript.py
echo %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 exit
exit(15)
sth
Bingo! Cheers :)
Kezzer
Errorlevel is only a pseudo-variable, it isn't actually anywhere in the environment.
Joey
This will NOT work if %ERRORLEVEL% variable already exists. Python will not overwrite it in that case (but does return the correct code - it will just be hidden by the variable!).
fmuecke
+2  A: 

Try:

import os
os._exit(ret_value)

You should also check:

Macarse
And thanks to you, both of your answers were correct, I just needed the other side to it from the bat file as well. Thanks again.
Kezzer