0

Everyone.

I'm trying to call a python function from a batch file, specifically inside an if statement (I'm using python 3.3.2). Suppose I have two variables %filePath% and %filePath2% and a python function in getFileRevision.py. Here is a piece of my batch script:

python getFileRevision.py %filePath%
set revision=%ERRORLEVEL%

python getFileRevision.py %filePath2%
set revision2=%ERRORLEVEL%

echo Before entering if statement:
echo revision=%revision%
echo revision2=%revision2%

python getFileRevision.py %filePath%
set revision=%ERRORLEVEL%

if exist %filePath2% (
    echo condition = true!
    python getFileRevision.py %filePath2%
    set revision2=%ERRORLEVEL%
)

echo revision=%revision%
echo revision2=%revision2%

I call the python function for two different arguments and print the return values. Then make this another time, but this time I call the python function inside an If statement. Here is what is print in my console:

    revision=109803
    revision2=109671
    condition = true!
    revision=109803
    revision2=109803

From this result, you can see that calling python function inside the If statement didn't change return value. Does anybody know the cause of this strange behavior and how to solve it?

Thanks anyway.

Bruno Caetano
  • 57
  • 1
  • 1
  • 5
  • where does the `%ERRORLEVEL%` come from? – chris-sc Aug 13 '15 at 12:37
  • %ERRORLEVEL% is an environment variable from batch that can be used to capture return value from python function. See this: http://stackoverflow.com/questions/1491796/get-the-exit-code-for-python-program – Bruno Caetano Aug 13 '15 at 12:43

1 Answers1

0

Inside a code block (any code within brackets) you can not use '%' to access latest variable values. You need to enabledelayedexpansion and use ! instead.

setlocal enabledelayedexpansion
python getFileRevision.py %filePath%
set revision=%ERRORLEVEL%

python getFileRevision.py %filePath2%
set revision2=%ERRORLEVEL%

echo Before entering if statement:
echo revision=%revision%
echo revision2=%revision2%

python getFileRevision.py %filePath%
set revision=%ERRORLEVEL%

if exist %filePath2% (
    echo condition = true!
    python getFileRevision.py %filePath2%
    set revision2=!ERRORLEVEL!
)

echo revision=%revision%
echo revision2=%revision2%

which should now work fine.

Monacraft
  • 6,510
  • 2
  • 17
  • 29