Reputation: 23
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()
Upvotes: 1
Views: 2501
Reputation: 96
Your question is a bit vague, so I'll give you some ideas to produce at least a reasonable solution. As usual, I invite you to post some code if you want a more detailed and specific answer.
First of all, check for tools which do what you asked. I know of py-mon, which seems to be nodemon for Python, but I never had the need to use it.
In case you don't like it, you can implement your subprocesses idea.
First, create an entry point for your script, ideally a function which does what you want to do when changes are detected.
Then make a watchdog.py
(or however you want to call it) file where you start the function in a subprocess, then kill the subprocess and start a new one when you detect change in observed folders via watchdog.
To implement it, start from the example in the watchdog pypi page and put a sprinkle of multiprocessing in it. Now, I don't know if it's feasible without a look at your code, but it seems at least a reasonable solution.
If you want to develop on this, post some code and we'll start from there, otherwise best of luck :-)
Upvotes: 0