在命令完成之前批量处理命令输出

问题描述 投票:0回答:1

我尝试打印命令输出的时间(例如 ping)。

echo([!time!] start
for /f "usebackq delims= eol=" %%A in (`ping ::1`) do (
  echo([!time!] __ %%A
)
echo([!time!] finish

但结果我得到了

[12:37:08.78] start
[12:37:12.04] __ Pinging ::1 with 32 bytes of data:
[12:37:12.04] __ Reply from ::1: time<1ms
[12:37:12.04] __ Reply from ::1: time<1ms
[12:37:12.04] __ Reply from ::1: time<1ms
[12:37:12.04] __ Reply from ::1: time<1ms
[12:37:12.04] __ Ping statistics for ::1:
[12:37:12.04] __     Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
[12:37:12.04] __ Approximate round trip times in milli-seconds:
[12:37:12.04] __     Minimum = 0ms, Maximum = 0ms, Average = 0ms
[12:37:12.04] finish

看起来只有在命令完成后才开始循环工作。 有没有办法在命令完成之前处理命令输出?

batch-file
1个回答
0
投票

FOR/F 不能用于异步处理。

但是可以通过使用两个线程和一个管道来解决。
Producer_thread 输出到文件,consumer_thread 用

set /p
读取所有数据,并在发现“EOF”字符串时停止。

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

cd. > async.tmp

"%~d0\:producer_thread:\..\%~pnx0" >> async.tmp | "%~d0\:consumer_thread:\..\%~pnx0" < async.tmp
echo END
exit /b

:producer_thread
ping ::1 -n 3 | find /n /v ""
(echo EOF)
exit /b

:consumer_thread
setlocal EnableDelayedExpansion

echo([!time!] start
for /L %%n in (1,1,256) do for /L %%n in (1,1,256) do for /L %%n in (1,1,256) do for /L %%n in (1,1,256) do (
  set "line="
  set /p "line="
  if "!line!" == "EOF" goto :exit_loop
  if defined line (
    set "line=!line:*]=!"
    echo([!time!] __ !line!
  )
)
:exit_loop
echo([!time!] finish
exit /b
© www.soinside.com 2019 - 2024. All rights reserved.