<filename>www/pymonitor.py
#!/usr/bin/env python3
# -*- coding:utf-8 -*-


"""
@version: ??
@usage: monitior for server
        if py file is changed
        can auto restart app.py
        '''
        python3 pymonitor.py wsgiapp.py
        ./pymonitor.py app.py
        '''

        '''
        $ ./pymonitor.py app.py
        [Monitor] Watching directory /Users/khrystal/PycharmProject/awesome-python3-webapp/www...
        [Monitor] Start process python app.py...
        ...
        INFO:root:application (/Users/khrystal/PycharmProject/awesome-python3-webapp/www) will start at 0.0.0.0:9000...
        [Monitor] Python source file changed: /Users/khrystal/PycharmProject/awesome-python-webapp/www/handlers.py
        [Monitor] Kill process [2712]...
        [Monitor] Process ended with code -9.
        [Monitor] Start process python app.py...
        ...
        INFO:root:application (/Users/khrystal/PycharmProject/awesome-python3-webapp/www) will start at 0.0.0.0:9000...
        '''
@author: kHRYSTAL
@license: Apache Licence 
@contact: <EMAIL>
@site: https://github.com/kHRYSTAL
@software: PyCharm
@file: pymonitor.py
@time: 16/6/2 上午7:53
"""

import os, sys, time, subprocess

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

def log(s):
    print('[Monitor] %s' % s)

class MyFileSystemEventHander(FileSystemEventHandler):

    def __init__(self, fn):
        super(MyFileSystemEventHander, self).__init__()
        self.restart = fn

    def on_any_event(self, event):
        if event.src_path.endswith('.py'):
            log('Python source file changed: %s' % event.src_path)
            self.restart()

command = ['echo', 'ok']
process = None

def kill_process():
    global process
    if process:
        log('Kill process [%s]...' % process.pid)
        process.kill()
        process.wait()
        log('Process ended with code %s.' % process.returncode)
        process = None

def start_process():
    global process, command
    log('Start process %s...' % ' '.join(command))
    process = subprocess.Popen(command, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)

def restart_process():
    kill_process()
    start_process()

def start_watch(path, callback):
    observer = Observer()
    observer.schedule(MyFileSystemEventHander(restart_process), path, recursive=True)
    observer.start()
    log('Watching directory %s...' % path)
    start_process()
    try:
        while True:
            time.sleep(0.5)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

if __name__ == '__main__':
    argv = sys.argv[1:]
    if not argv:
        print('Usage: ./pymonitor your-script.py')
        exit(0)
    if argv[0] != 'python3':
        argv.insert(0, 'python3')
    command = argv
    path = os.path.abspath('.')
    start_watch(path, None)
<filename>www/pymonitor.py
#!/usr/bin/env python3
# -*- coding:utf-8 -*-


"""
@version: ??
@usage: monitior for server
        if py file is changed
        can auto restart app.py
        '''
        python3 pymonitor.py wsgiapp.py
        ./pymonitor.py app.py
        '''

        '''
        $ ./pymonitor.py app.py
        [Monitor] Watching directory /Users/khrystal/PycharmProject/awesome-python3-webapp/www...
        [Monitor] Start process python app.py...
        ...
        INFO:root:application (/Users/khrystal/PycharmProject/awesome-python3-webapp/www) will start at 0.0.0.0:9000...
        [Monitor] Python source file changed: /Users/khrystal/PycharmProject/awesome-python-webapp/www/handlers.py
        [Monitor] Kill process [2712]...
        [Monitor] Process ended with code -9.
        [Monitor] Start process python app.py...
        ...
        INFO:root:application (/Users/khrystal/PycharmProject/awesome-python3-webapp/www) will start at 0.0.0.0:9000...
        '''
@author: kHRYSTAL
@license: Apache Licence 
@contact: <EMAIL>
@site: https://github.com/kHRYSTAL
@software: PyCharm
@file: pymonitor.py
@time: 16/6/2 上午7:53
"""

import os, sys, time, subprocess

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

def log(s):
    print('[Monitor] %s' % s)

class MyFileSystemEventHander(FileSystemEventHandler):

    def __init__(self, fn):
        super(MyFileSystemEventHander, self).__init__()
        self.restart = fn

    def on_any_event(self, event):
        if event.src_path.endswith('.py'):
            log('Python source file changed: %s' % event.src_path)
            self.restart()

command = ['echo', 'ok']
process = None

def kill_process():
    global process
    if process:
        log('Kill process [%s]...' % process.pid)
        process.kill()
        process.wait()
        log('Process ended with code %s.' % process.returncode)
        process = None

def start_process():
    global process, command
    log('Start process %s...' % ' '.join(command))
    process = subprocess.Popen(command, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)

def restart_process():
    kill_process()
    start_process()

def start_watch(path, callback):
    observer = Observer()
    observer.schedule(MyFileSystemEventHander(restart_process), path, recursive=True)
    observer.start()
    log('Watching directory %s...' % path)
    start_process()
    try:
        while True:
            time.sleep(0.5)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

if __name__ == '__main__':
    argv = sys.argv[1:]
    if not argv:
        print('Usage: ./pymonitor your-script.py')
        exit(0)
    if argv[0] != 'python3':
        argv.insert(0, 'python3')
    command = argv
    path = os.path.abspath('.')
    start_watch(path, None)
#!/usr/bin/env python3 # -*- coding:utf-8 -*- @version: ?? @usage: monitior for server         if py file is changed         can auto restart app.py         '''         python3 pymonitor.py wsgiapp.py         ./pymonitor.py app.py         '''          '''         $ ./pymonitor.py app.py         [Monitor] Watching directory /Users/khrystal/PycharmProject/awesome-python3-webapp/www...         [Monitor] Start process python app.py...         ...         INFO:root:application (/Users/khrystal/PycharmProject/awesome-python3-webapp/www) will start at 0.0.0.0:9000...         [Monitor] Python source file changed: /Users/khrystal/PycharmProject/awesome-python-webapp/www/handlers.py         [Monitor] Kill process [2712]...         [Monitor] Process ended with code -9.         [Monitor] Start process python app.py...         ...         INFO:root:application (/Users/khrystal/PycharmProject/awesome-python3-webapp/www) will start at 0.0.0.0:9000...         ''' @author: kHRYSTAL @license: Apache Licence  @contact: <EMAIL> @site: https://github.com/kHRYSTAL @software: PyCharm @file: pymonitor.py @time: 16/6/2 上午7:53