JarsOfJam-Scheduler
JarsOfJam-Scheduler

Reputation: 3169

My Python script that waits for a file to be present in a directory iterates too much at the level of the verification of this presence

I have created a Python script that needs a file to be present in a directory. This file is for example downloaded from a browser (for example with Selenium). The workflow that I've imaginated is the following:

  1. Imagine an action that may create the file in the wanted directory (for example, download with Selenium in the Windows/Linux's default directory of downloads)
  2. For a maximum of 10 times, try to execute this action and wait for 10 seconds
  3. For each time, after these 10 seconds, check if the file is present in the directoy: if yes, break the loop and continue the script since now it has the wanted file. If no, continue the loop until the 10 times (or less) are done.
  4. When the 10 times are done and that the file is still not present in the directory, raise a fatal error

My problem

Even if the file is present in the directory, the loops is executed 10 times instead of being broken.

The script (minimal and executable example)

Sources

    file_was_downloaded = False
    for u in range(10):
        click(Link('download the file in the directory'))
        time.sleep(10)
        files = os.listdir('C:/Users/XYZ/Downloads/')
        for f in files:
            if f.startswith("the_file.jpg") and not f.endswith(".crdownload"):  # ".crdownload" if a suffix appended to the name of the file by Google Chromium/Chrome if it's not completely downloaded
                file_was_downloaded = True
                break
    if not file_was_downloaded:
       print(datetime.datetime.now() + " - The file may not be present in the directory.\n")
       exit(-1)
    
    # Below this line, we can use the file.

Test

You can remove the line click and replace it by yourself adding the wanted file in the directory when you want, while the script is running. You will see that the loop will continue to iterate even if the file is in the directory. That's the problem and I don't know why it behaves like this.

Expected behavior

When the file is detected as "present" in the directory, the loop breaks.

Actual behavior

The loop continues to iterate.

Upvotes: 1

Views: 745

Answers (2)

Ktoto
Ktoto

Reputation: 91

Try something like this:

import time

for i in range(10):
    '''your donwload code'''
    try:
        file = open("yourfile.jpg")
        break
    except:
        time.sleep(10)

Upvotes: 0

Saxasmu
Saxasmu

Reputation: 384

Your break statement only breaks the "for f in files" loop. add another if in the "for u in range" loop:

if file_was_downloaded:
   break
  

Upvotes: 2

Related Questions