It's difficult to explain what I've been trying to accomplish and my shallow knowledge does not allow me to resolve this doubt, for this reason I came here to ask for help.
I have an n1 program in python that performs a function if a txt file has its KB size equal to or greater than "1" and will not activate the function if the same file has its KB size equal to or less than "0". As you may know, the way to do this is very simple. However, this n1 program only knows if this file has changed if it performs this check. And to keep it constantly up to date I do an uninterrupted check with a loop:
#n1 program
import os
def functionInative() {
#only activated if file KB == or > 1
}
while True:
if os.stat(path-file).st_size > 0:
functionIntive() # now activate functino
else:
pass
When the function is executed it will do its tasks and at the end it will clean the file so that if any new information arrives in the file, it will be noticed and the process will be repeated. For this reason I can't use something like a "break" either.
However, I wondered if it would be possible to let these programs somehow "stand still" and activate the function only when the file is filled. No need for an infinite loop checking the file until there is any modification.
It would be something like real-time PUSH or CHATS notifications. There is no free way a loop checking for new messages. It is simply only when they arrive that the functions are activated.
I hope you have understood my big question.
CodePudding user response:
What you are asking about is a file watcher.
Your method of polling the file is fine actually. To avoid using up a lot of CPU cycles, you should probably add a time.sleep(0.1)
call so that it is not checking nearly as often.
Although, Watchdog is a module in Python that will do exactly what you are asking and provide events that will call your function if a file changes.
Here is an example from their documentation: https://pythonhosted.org/watchdog/quickstart.html#a-simple-example