views:

156

answers:

1

I need some assistance writing what should be a fairly basic .BAT file.

I load my main program, but that program takes ~20secs to load and be initialized.

I have another command-line API I can execute to interact with this above program, but obviously until the above program is loaded and initialized there's no point in trying.

If the program isn't running the command-line API returns a string stating exactly this - otherwise it just works and exits. Easy.

So I want to wait until the above is loaded/initialized before firing my API command(s) at it.

I could place a sleep/wait in there, but I want something more solid. The ~20sec wait is not necessarily consistent.

Any way to execute the command-line API over and over until the response is satisfactory, then exit?

J

A: 

Of course. However, you should probably consider an appropriate exit code instead of a message string to signify that loading isn't complete yet. Unless the output is never localized there.

Anyway, here we go:

:loop
yourcommand.exe | findstr MAGIC STRING SIGNIFYING LOADING NOT YET COMPLETE >nul 2>&1
if not errorlevel 1 goto loop

This simply retries as long as the findstr there returns 0 as its exit code (meaning it found the string).

Two problems with this, though:

  1. It's a resource hog. You should put a sleep in there to try every other second or so instead of doing it continuously:

    ping -n 1 ::1 >nul 2>&1
    
  2. While this will run your intended command at most once (in the end), it eats all output since it pipes it to findstr. Unless you have tee at hand that's difficult to resolve (it would involve a for loop over the output and checking each line with findstr – you don't want to go there, believe me.

    An option might be if there was a way for your command to just check and then issue the actual commands with a call after the loop (which exists when the program was found to be working). You could then happily log all output. However, if the program you're talking to goes down between exiting the loop and launching the program with the actual commands you got another problem.

Joey
Jason N
Redirects error output (stream 2) to the same location where stream 1 (stdout) is going. In this case NUL. If you just redirect to NUL it's not actually needed, just muscle memory by now. But if you redirect into files you can't do `foo 1>a.txt 2>b.txt` because then only one stream can go into the file (you can't open it twice for writing). In hindsight, I don't think `findstr` will ever write something to stderr here – again, redirecting both is muscle memory for me :-)
Joey