How to print output while executable is running in windows batch for loop?

Viewed 737

I am using a for loop to execute another executable and capturing the output. The output is a set of variables such as

Name=Jim
Address=1234 Main Ave
Phone=425-555-0202

However it takes quite a while for this executable to run. I am capturing the output and setting environment variables via:

for /f "tokens=*" %%a in ('fetch.exe <options>') do (
    echo "%%a"
    set "%%a"
)

This is working fine, however if fetch.exe takes 120 seconds to run, the echo portion of that loop does not run until after the process is completed 120 seconds later. An easy test is to create a batch file such as

@echo 1
@echo 2
@echo 3
@echo 4
timeout /t 30

Then call that from the command line via for /f "tokens=*" %a in ('call test.cmd') do (@echo "%a")

You will not see any output for 30 seconds.

How can I immediately start seeing the output of the command being executed?

1 Answers

As said, FOR /F can't handle this, as it waits for the completion of the invoked command.

But you can get it working with an async pattern.
The producer works in its own thread.

@echo off
REM *** Trampoline jump for function calls of the form ex. "C:\:function:\..\MyBatchFile.bat"
FOR /F "tokens=3 delims=:" %%L in ("%~0") DO goto :%%L

break > async.tmp
start "" /b "cmd /c "%~d0\:producer:\..\%~pnx0"
call :consumer
exit /b

:producer
(
  call slowOutput.bat 
  (echo ende)
) > async.tmp
exit /b

:consumer
echo c
setlocal EnableDelayedExpansion
< async.tmp call :_consumer
exit /b

:_consumer
set "line="
set /p line=

if not defined line goto :_consumer
if "!line!" EQU "ende" exit /b

echo(!line!
goto :_consumer
Related