简体   繁体   English

批处理文件中的“EXIT”不能覆盖以前命令的返回代码

[英]“EXIT” in batch file cannot overwrite return code of previous commands

Running this batchfile from the Windows commandline results in an %errorlevel% of 5 (ie running echo %errorlevel% on the commandline after having executing the batch file prints the number 5): 从Windows命令行运行此批处理文件会导致%errorlevel%为5(即在执行批处理文件后,在命令行上运行echo %errorlevel%打印数字5):

EXIT /B 5

This is fine. 这可以。

However, running this batchfile results in an %errorlevel% of 0, no matter what: 但是,运行此批处理文件会导致%errorlevel%为0,无论如何:

sleep 1
EXIT /B 5

I want it to return the error code 5. How can I do that? 我希望它返回错误代码5.我怎么能这样做?

Note: If I add sys.exit(13) to the sleep.py (see below), then the second batch file will return with an exit code of 13. So my batch file will return with the exit code of the sleep.py script instead of the exit code specified via the EXIT command (which is strange). 注意:如果我将sys.exit(13)添加到sleep.py(见下文),那么第二个批处理文件将返回退出代码为13.所以我的批处理文件将返回sleep.py的退出代码脚本而不是通过EXIT命令指定的退出代码(这很奇怪)。


sleep.bat: sleep.bat:

sleep.py %1

sleep.py: sleep.py:

import sys
import time

if len(sys.argv) == 2:
    time.sleep(int(sys.argv[1]))

sleep is a batch file. sleep是一个批处理文件。 When calling a batch file from another batch file this way, control never returns to the caller (akin to exec in POSIX). 当以这种方式从另一个批处理文件调用批处理文件时,控件永远不会返回给调用者(类似于POSIX中的exec )。 Use call sleep 1 instead. 请改用call sleep 1

Or just sleep with built-in programs: 或者只是睡觉内置程序:

:sleep1
setlocal
set /a X=%~1 + 1
ping ::1 -n %X% >nul 2>&1
endlocal
goto :eof

:sleep2
timeout /T %1 /nobreak
goto :eof

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

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