简体   繁体   中英

strange behavior when calling python function inside if statement in batch file

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM