-
Notifications
You must be signed in to change notification settings - Fork 0
/
monitor_and_restart.py
48 lines (40 loc) · 1.42 KB
/
monitor_and_restart.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import sys
import time
import subprocess
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class RestartHandler(FileSystemEventHandler):
def __init__(self, script):
self.script = script
self.process = None
self.restart_script()
def restart_script(self):
if self.process:
self.process.terminate()
self.process.wait()
self.process = subprocess.Popen([sys.executable, self.script])
def on_modified(self, event):
if event.src_path.endswith('.py'):
print(f"{event.src_path} has been modified. Restarting script.")
self.restart_script()
def on_created(self, event):
if event.src_path.endswith('.py'):
print(f"{event.src_path} has been created. Restarting script.")
self.restart_script()
def on_deleted(self, event):
if event.src_path.endswith('.py'):
print(f"{event.src_path} has been deleted. Restarting script.")
self.restart_script()
if __name__ == "__main__":
path = "." # Watch the current directory
script_to_watch = "bot.py"
event_handler = RestartHandler(script_to_watch)
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()