-1

Ive got some subprocesses running and stdout txt files are located in output folder. I'd like to wait for all subprocesses by looping thru all files in output folder if they'll have "exit" string which is always on the end in the process writen in the stdout txt file. Thanks for any help.

this is what i've got:

    for file in glob.glob("filename*.txt"):
        with open(file, "r").read() as f:
            if "exit" in f:
                break

but it will break when one of the files will have exit. Should While False on start be a good solution? and instead of break put continue?

Lucas
  • 93
  • 2
  • 12
  • Start with writing code that lists all the files in a given folder. [Hint](http://stackoverflow.com/questions/3207219/how-to-list-all-files-of-a-directory-in-python) [Hint](http://stackoverflow.com/questions/3964681/find-all-files-in-directory-with-extension-txt-in-python). After you have the code to list all the files, then ask your question again. Asking for code on SO is just looking for your question to be closed. – smac89 Dec 13 '16 at 20:25
  • sorry for not puttng my code. i just dont know how to end a loop when all of those files will fulfill condition – Lucas Dec 13 '16 at 20:30

1 Answers1

0

You need to loop until your condition is satisfied. You can accomplish this using break inside a while True: loop.

file_names = glob.glob("/tmp/foo*.txt")
while True:
    if not file_names:
        break
    for file_name in file_names:
        with open(file_name, "r") as f:
            if "exit" in f.read():
                file_names.remove(file_name)

Here it's entering an infinite loop that will only exit once the file_names variable is empty. If it's not empty it loops over that variable, opens and reads the file. If the file contains "exit" then it removes that file name from the list.

You may want to consider performing a time.sleep so you're not thrashing the filesystem but that depends on how long you anticipate waiting. Perhaps a timeout as well.

joebeeson
  • 4,159
  • 1
  • 22
  • 29
  • For robustness it may be a good idea to sharpen the OP's spec so that the keyword "exit" must occur alone on a line – jez Dec 13 '16 at 22:36