Siavash
Siavash

Reputation: 7853

how to look for occurrence of a string, in out put of a command, in a batch file

I have a python script that does a test and prints pass or fail to the command line. I want to run this script from a batch file continuously until it fails. So I need to parse the output of the script from inside my batch file and either "goto start" or continue to end of the batch file.

I did some research and it seems like I need to use the for /f command, but I dont know how to look for a string in the entire out put.

lets say my script is called test.py and I want to look for the string "PASS" in its output. What is the exact syntax to use the for /f command?

I am also open to other solutions.

Upvotes: 0

Views: 82

Answers (3)

brianadams
brianadams

Reputation: 233

instead of doing it in batch, why not do it in your test.py ?

while true:
    ... do your stuff
    ... 
    if result == "FAIL"
        break
call some other commands ....

Upvotes: -1

Magoo
Magoo

Reputation: 80213

You don't need to use FOR /F at all.

@echo off
:loop
test.py|find /i "pass" >nul
if NOT errorlevel 1 goto loop

If python outputs any line containing pass (the /i makes it case-insensitive - find "PASS" would be case-sensitive) then errorlevel is set to 0 otherwise, errorlevel is set >0.

IF ERRORLEVEL n is TRUE if errorlevel is n OR GREATER THAN n. IF ERRORLEVEL 0 is therefore always true, so you need if not errorlevel 1 to test for errorlevel 0.

Upvotes: 1

unclemeat
unclemeat

Reputation: 5207

If you want the script to continue if the output of your python script is PASS then this should do the trick -

:loop
For /F %%a in ('test.py') do set output=%%a
if "%output%"=="PASS" goto :loop

If you don't add anything after the final if statement there it will just end the script, if you want you can just add goto :EOF (End Of File) after the if statement.

Upvotes: 1

Related Questions