I am trying to restart a python process, when file changes are made.
Dir Structure
/root
|_ test.py
|_ main.py
main.py
import os
import sys
import shutil
import _thread
import subprocess
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler, FileSystemEvent
cwd = os.getcwd()
pj = os.path.join
exists = os.path.exists
class Reloader(FileSystemEventHandler):
def __init__(self, openProc: subprocess.Popen = None, cmd=""):
super().__init__()
self.__cmd = cmd
self.openProc = openProc if openProc else subprocess.Popen(self.__cmd, cwd=cwd, shell=True)
def on_any_event(self, event):
if event.is_directory:
return
_, ext = os.path.splitext(event.src_path)
if ext[1:] in ["py", "cpp", "c", "h", "hpp"]:
print(":: CHANGES DETECTED, RELOADING ::")
print("--changed file '{}'--".format(event.src_path))
self.killProc()
def killProc(self):
self.openProc.kill()
def getInput():
global cwd
cwd = os.getcwd()
return input("⚡>" + cwd + ">")
if __name__ == "__main__":
while True:
userInput = getInput()
split = userInput.split(" ")
print("Starting CMD Command With Reloader...")
while True:
try:
event_handler = Reloader(cmd=split)
observer = Observer()
observer.schedule(event_handler, cwd, recursive=True)
observer.start()
while event_handler.openProc.poll() is None:
pass
observer.stop()
except KeyboardInterrupt:
break
test.py
import time
c = 0
while True:
c+=1
print(c)
time.sleep(1)
When I run that:
E:\electrocli>py main.py
⚡>E:\electrocli>py test.py
Starting CMD Command With Reloader...
1
2
3
4
:: CHANGES DETECTED, RELOADING ::
--changed file 'E:\electrocli\test.py'--
:: CHANGES DETECTED, RELOADING ::
--changed file 'E:\electrocli\test.py'--
5
1
6
2
7
3
This shows that, the older process, whis should be revoked by subprocess.Popen.kill
has not ended. I want to kill the old process, and start the new one. Is there any way to do that? Or, is there any mistake in my code?