Reputation: 89
I'm trying to create a simple file renamer using watchdog in python, it is very simple, any created "xlsx" file will be rename to "Base.xslx"
I got it quickly by using the code below, but when running it uses a lot of CPU and power, is there anything wrong with the code itself or this is normal?
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import time
import os
fp = 'C:/yourpath/'
class ExampleHandler(FileSystemEventHandler):
def on_created(self, event):
time.sleep(1)
for file_name in os.listdir(fp):
if '.xlsx' in file_name:
name=fp+file_name
os.rename(name,"Base.xlsx")
observer = Observer()
event_handler = ExampleHandler()
observer.schedule(event_handler, path=fp)
observer.start()
try:
while True:
time.sleep(0)
except KeyboardInterrupt:
observer.stop()
observer.join()
Upvotes: 2
Views: 1439
Reputation: 11
For me it seems that time.sleep(0)
is one of the problems. Observer class is event based, so it isn't monitoring the folder according to the parameter of the sleep in the infinite cycle, but it's going to run the handler method as soon as the event is arrived from the OS.
This infinite cycle is using a whole CPU core (as empty infinite cycles usually do), so you should change the time.sleep()
parameter to 1
(or anything else bigger than that, it won't matter as KeyboardInterrupt
will interrupt the sleep method regardless its 'length').
Also you should use PatternMatchingEventHandler()
, it has almost the same functionality as yours but it only examine the newly created file (not every file, for each handler method call), and you don't even need to write any new class.
Upvotes: 1