Created
November 8, 2016 17:11
-
-
Save abijith-kp/27ff708f787760c4395404ee2f6a5c5b to your computer and use it in GitHub Desktop.
Monitor file change for a python script and restart the script automatically.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pyinotify | |
import sys | |
import subprocess | |
import os | |
import click | |
def restart(filename): | |
p = subprocess.Popen(['python', filename]) | |
print("Process ID of subprocess %s" % p.pid) | |
return p | |
class MyEventHandler(pyinotify.ProcessEvent): | |
_process = None | |
_filename = None | |
def process_IN_CLOSE_WRITE(self, event): | |
print(event.pathname) | |
if os.path.basename(event.pathname) != self._filename: | |
return | |
if self._process: | |
self._process.terminate() | |
returncode = self._process.wait() | |
print("Returncode of subprocess: %s" % returncode) | |
self._process = restart(self._filename) | |
print('process restarted') | |
@click.command() | |
@click.option('-f', '--filename', help='filename to be monitored') | |
@click.option('-d', '--directory', default='.', | |
help='directory where the file is present') | |
def cli(filename, directory): | |
print('Watching file:', filename) | |
wm = pyinotify.WatchManager() | |
wm.add_watch(directory, pyinotify.IN_CLOSE_WRITE, rec=True) | |
eh = MyEventHandler() | |
eh._process = restart(filename) | |
eh._filename = filename | |
notifier = pyinotify.Notifier(wm, eh) | |
notifier.loop() | |
if __name__ == '__main__': | |
cli() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment