0

I am looking for a way to keep my python script watching a directory for any new file, so that my script can execute that added file. I don't want to strain my CPU with a while loop that keeps on running the script checking at each and every while loop cycle straining the CPU, on the other hand, the sleep function only limits the script to run after a designated time, thus the sleep function is not flexible to new changes, it runs on specific intervals hence not efficient.

Is there a method using the sleep function that waits until a certain file is added, then triggers the script to run instantly without exiting the script.

As I mentioned above, when it runs this new added file(the code for running the latest added file I already have it, I made use of the os.stat function which allows me to pick the latest file and store it in a list), I want to keep the script watching without exiting, that is to say it will be in a sleep mode, to reduce CPU usage, and is only triggered again when a new file is in the directory.

How best can I attack this trigger mechanism without straining CPU with the continuously running while loop and also without using the inflexible sleep function which only checks for changes after certain intervals.

I want the script to be highly autonomous, that is to say, it's only activated when a new file is added and go back to sleep again when done processing, then wakes up(is triggered) when a new file is detected in the directory.

Regards Wisdom.

  • Tags are for what your question is about - nothing in your question pertains to "tensorflow", "artificial-intelligence", "dcmtk" or "orthanc-server" so I removed them. Check out the many duplicates on SO already that helps you solve your problem. You may also want to check superuser for more OS-centric approaches - nobody tells you you need a python script to do the detection, there may be OS-centric ways to trigger a python script when a new file pops into a watched folder. – Patrick Artner Mar 06 '22 at 11:17
  • Thank you again, I used an OS-centric approach as you mentioned. I used Watchman service for Linux. It really suited my request. (Watchman – A File and Directory Watching Tool for Changes).https://www.tecmint.com/watchman-monitor-file-changes-in-linux/ – Wisdom James Murombo Mar 13 '22 at 17:32

0 Answers0