批处理!ERRORLEVEL! 运行 多个命令并行时不工作

Batch process !ERRORLEVEL! is not working when running multiple commands in parallel

我正在尝试创建一个批处理脚本,其中 运行s 2 python 并行脚本和 return 如果其中一个(或两个)脚本中的错误代码是错误。如果两个脚本都正确 运行 下一个 python 脚本应该是 运行.

当我使用下面的脚本时,进程是 运行 并行的,但是 !errorlevel!始终为 0,即使两个脚本中都存在错误。

如果我 运行 只有一个 python 脚本带有 start /wait 命令,或者如果我 运行 2 个脚本依次使用 && 而不是 |,则 !errorlevel ! return编辑正确。

这些脚本如何 运行 并行,同时仍然输出正确的错误级别?

setlocal enableDelayedExpansion
start /wait python apirequest_0001.py | start /wait python apirequest_0002.py
echo !errorlevel!
if !errorlevel! neq 0 (goto end )
start /wait python join_data.py

这里有几点...

start命令用于运行一个并行进程,但是start /wait开关取消了这样的功能,等待过程结束。这样一来,使用start /wait就等于根本没有使用启动命令...

但是,在您的示例中,两个命令都通过管道连接,因此它们实际上是并行执行的(因为是管道,而不是 start 命令)。

获取两个(或更多)并行进程的 ERRORLEVEL 值的最简单方法是通过辅助文件:

del error.aux 2> NUL
(python apirequest_0001.py & if errorlevel 1 echo X > error.aux) | (python apirequest_0002.py & if errorlevel 1 echo X > error.aux)
if exist error.aux goto end
python join_data.py

虽然“更干净”的方法是通过

del error.aux 2> NUL
(
  start "" "python apirequest_0001.py & if errorlevel 1 echo X > error.aux"
  start "" "python apirequest_0002.py & if errorlevel 1 echo X > error.aux"
) | pause
if exist error.aux goto end
python join_data.py

注意:在此解决方案中,两个命令可能同时结束并尝试“同时”创建文件。但是,这不是问题,因为无论如何都会创建文件...