Home > Software design >  Batch process !ERRORLEVEL! is not working when running multiple commands in parallel
Batch process !ERRORLEVEL! is not working when running multiple commands in parallel

Time:02-16

I am trying to create a batch script which runs 2 python scripts in parallel and return an errorcode if in either one (or both) of the scripts is an error. In case both script have run correctly the next python script should be ran.

When I use the script below the processes are ran in parallel but the !errorlevel! is always 0, even if there is an error in both of the scripts.

In case I run only one of the python scripts with the start /wait command or if I run the 2 scripts sequentially using && instead of |, the !errorlevel! is returned correctly.

How can these scripts be run in parallel while still output the correct errorlevel?

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

CodePudding user response:

A couple points here...

The start command is used to run a process in parallel, but start /wait switch cancel such a feature and waits for the process to end. In this way, using start /wait is the same as no use start command at all...

However, in your example both commands are connected via a pipeline, so they are effectively executed in parallel (because the pipe, not the start command).

The simplest way to get the ERRORLEVEL value of two (or more) parallel processes is via an auxiliary file:

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

Although a "cleaner" way to do this is via this method

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

Note: In this solution there is a possibility that both commands ends at the same time and try to create the file at "same time". However, this is not a problem in the case, because anyway the file will be created...

  • Related