简体   繁体   English

在批处理文件中的if语句中调用python函数时出现奇怪的行为

[英]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). 我正在尝试从批处理文件中调用python函数,尤其是在if语句内部(我正在使用python 3.3.2)。 Suppose I have two variables %filePath% and %filePath2% and a python function in getFileRevision.py . 假设我在getFileRevision.py中有两个变量%filePath%和%filePath2%和一个python函数。 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. 我为两个不同的参数调用python函数,并输出返回值。 Then make this another time, but this time I call the python function inside an If statement. 然后再做一次,但是这次我在If语句中调用python函数。 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. 从这个结果中,您可以看到在If语句中调用python函数并没有改变返回值。 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 ! 您需要enabledelayedexpansion并使用! 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. 现在应该可以正常工作了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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