I would like to implement an automatic restart option in my script(script will restart itself on any change, like deletion or creation of the file in a directory). I need it to be cross-platform, and I am able to get events on file changes using watchdog. My questions is, how can I properly restart file itself after getting event from watchdog? Using os.exec* family didn't help, so I think using subprocess would fix the issue: I need to replace current process with a new launched one. Any ideas?
Here's the code I am launching:
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
print('STARTED THE SCRIPT')
class Handler(FileSystemEventHandler):
def on_any_event(self, event):
# i need to restart the script itself here.
pass
if __name__ == "__main__":
path = sys.argv[1] if len(sys.argv) > 1 else '.'
event_handler = Handler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
finally:
observer.stop()
observer.join()