Home > OS >  Bat script read output of command prompt
Bat script read output of command prompt

Time:01-12

I am trying to read the last line from a command prompt as I have another program running which will play a game and in the end echo if I am the winner, loser or we went to a draw. I have this sample code:

Edit: the section "------" isjust an example of what I am trying to achieve. Basically I want to read the line saying e.g. "Player: me win the game!" or "The game was a draw!" so the line was trying to indicate what I want to scan through the line and check if it contains either win, draw else it's a loss

@set win=0
@set draw=0
@set lose=0
@set loopcount=10

:loop
C:\battlesnakeCLI\battlesnake.exe play -W 11 -H 11 --name me --url http://localhost/api/gamev2 --name other --url http://localhost/api/gametest

------
if line.contains("win")
set /a win=win 1
else if (line.contains("draw")
set /a draw=draw 1
else
set /a lose=lose 1
------

set /a loopcount=loopcount-1
if %loopcount%==0 goto exitloop
goto loop
:exitloop

@ECHO Wins: %win% & echo:Draws: %draw% & echo:Losses:%lose%
pause

CodePudding user response:

I eventually came up with this solution:

@set win=0
@set draw=0
@set lose=0
@set loopcount=10

:loop
C:\battlesnakeCLI\battlesnake.exe play -W 11 -H 11 --name me --url http://localhost/api/gamev2 --name other --url http://localhost/api/gametest 1> out.txt 2>&1 | type out.txt
@findstr /c:"me is the winner" "out.txt" >nul 2>&1
@if %errorlevel%==0 (
    @set /a win=win 1
) 
@findstr /c:"It was a draw" "out.txt" >nul 2>&1
@if %errorlevel%==0 (
    @set /a draw=draw 1
) 
@findstr /c:"other is the winner" "out.txt" >nul 2>&1
@if %errorlevel%==0 (
    @set /a lose=lose 1
)
@ECHO Wins: %win% & echo:Draws: %draw% & echo:Losses: %lose%
@del out.txt

@set /a loopcount=loopcount-1
@if %loopcount%==0 goto exitloop
@goto loop
:exitloop

@ECHO FINISHED RUNNING! Final scores: & echo:Wins: %win% & echo:Draws: %draw% & echo:Losses: %lose%
@PAUSE

CodePudding user response:

a shortened version of your code, untested:

@echo off
set win=0 & set draw=0 & set lose=0 & set loopcount=10

:loop
"C:\battlesnakeCLI\battlesnake.exe" play -W 11 -H 11 --name me --url http://localhost/api/gamev2 --name other --url http://localhost/api/gametest 1> out.txt 2>&1
findstr /c:"me is the winner" "out.txt" >nul 2>&1 && set /a win=win 1
findstr /c:"It was a draw" "out.txt" >nul 2>&1 && set /a draw=draw 1
findstr /c:"other is the winner" "out.txt" >nul 2>&1 && set /a lose=lose 1
ECHO Wins: %win% & echo:Draws: %draw% & echo:Losses: %lose%
del out.txt

set /a loopcount-=1
if %loopcount% gtr 0 goto loop
:exitloop

ECHO FINISHED RUNNING! Final scores: & echo:Wins: %win% & echo:Draws: %draw% & echo:Losses: %lose%
pause

The conditional operator && helps to not have to set parenthesized code blocks. Also getting rid of the overhead of @ everywhere and using the age old @echo off

  •  Tags:  
  • Related