def cli(*args): args = args or sys.argv[1:] parser = argparse.ArgumentParser( prog='watchgod', description= 'Watch a directory and execute a python function on changes.') parser.add_argument('function', help='Path to python function to execute.') parser.add_argument( 'path', nargs='?', default='.', help='Filesystem path to watch, defaults to current directory.') parser.add_argument('--verbosity', nargs='?', type=int, default=1, help='0, 1 (default) or 2') arg_namespace = parser.parse_args(args) log_level = { 0: logging.WARNING, 1: logging.INFO, 2: logging.DEBUG }[arg_namespace.verbosity] hdlr = logging.StreamHandler() hdlr.setLevel(log_level) hdlr.setFormatter( logging.Formatter(fmt='[%(asctime)s] %(message)s', datefmt='%H:%M:%S')) wg_logger = logging.getLogger('watchgod') wg_logger.addHandler(hdlr) wg_logger.setLevel(log_level) try: import_string(arg_namespace.function) except ImportError as e: print('ImportError: {}'.format(e), file=sys.stderr) return sys.exit(1) path = Path(arg_namespace.path) if not path.is_dir(): print('path "{}" is not a directory'.format(path), file=sys.stderr) return sys.exit(1) path = path.resolve() try: tty_path = os.ttyname(sys.stdin.fileno()) except OSError: # fileno() always fails with pytest tty_path = '/dev/tty' except AttributeError: # on windows. No idea of a better solution tty_path = None logger.info('watching "%s/" and reloading "%s" on changes...', path, arg_namespace.function) set_start_method('spawn') run_process(path, run_function, args=(arg_namespace.function, tty_path), callback=callback)
def watch_for_flush(context): "Flushes redis cache on reload" site = get_site(context) run_process( '../apps/', flushall, args=(site, ), min_sleep=4000, callback=show_changes, )
def cli(*args): args = args or sys.argv[1:] parser = argparse.ArgumentParser( prog='watchgod', description='Watch a directory and execute a python function on changes.' ) parser.add_argument('function', help='Path to python function to execute.') parser.add_argument('path', nargs='?', default='.', help='Filesystem path to watch, defaults to current directory.') parser.add_argument('--verbosity', nargs='?', type=int, default=1, help='0, 1 (default) or 2') parser.add_argument('--ignore-paths', nargs='*', type=str, default=[], help='Specify paths to files or directories to ignore their updates') parser.add_argument( '--args', '-a', nargs=argparse.REMAINDER, help='Arguments for argparser inside executed function. Ex.: module.func path --args --inner arg -v', ) arg_namespace = parser.parse_args(args) log_level = {0: logging.WARNING, 1: logging.INFO, 2: logging.DEBUG}[arg_namespace.verbosity] hdlr = logging.StreamHandler() hdlr.setLevel(log_level) hdlr.setFormatter(logging.Formatter(fmt='[%(asctime)s] %(message)s', datefmt='%H:%M:%S')) wg_logger = logging.getLogger('watchgod') wg_logger.addHandler(hdlr) wg_logger.setLevel(log_level) sys.path.append(os.getcwd()) try: import_string(arg_namespace.function) except ImportError as e: print('ImportError: {}'.format(e), file=sys.stderr) return sys.exit(1) path = Path(arg_namespace.path) if not path.exists(): print('path "{}" does not exist'.format(path), file=sys.stderr) return sys.exit(1) path = path.resolve() try: tty_path = os.ttyname(sys.stdin.fileno()) except OSError: # fileno() always fails with pytest tty_path = '/dev/tty' except AttributeError: # on windows. No idea of a better solution tty_path = None logger.info('watching "%s" and reloading "%s" on changes...', path, arg_namespace.function) set_start_method('spawn') sys.argv = sys_argv(arg_namespace.function) ignored_paths = {str(Path(p).resolve()) for p in arg_namespace.ignore_paths} run_process(path, run_function, args=(arg_namespace.function, tty_path), callback=callback, watcher_kwargs={'ignored_paths': ignored_paths})
def gevent_worker(queue, quiet=False, no_reload=False): if not queue: raise Exception('Cannot run worker without queue') if no_reload: start_gevent_background_worker(queue, quiet) else: run_process( '../apps/', start_gevent_background_worker, args=(queue, quiet), min_sleep=4000, callback=show_changes, )
def start_aio_dispatcher_worker(context, queue, noreload=False): site = get_site(context) log.debug("dispatcher - queue - {}, reloader - {}".format( queue, not noreload)) if noreload: start_aio_dispatcher(site, queue) else: run_process( '../apps/', start_aio_dispatcher, args=(site, queue), min_sleep=4000, )
def filewatch_worker(queue, filename): def on_changed(queue, filename): with open(filename, "r") as f: new_nb = json.load(f) queue.put(new_nb) sys.stderr = open(os.devnull, "w") sys.stdout = open(os.devnull, "w") filename = os.path.realpath(filename) start_dir = os.path.dirname(filename) run_process(start_dir, on_changed, watcher_cls=RegExpWatcher, watcher_kwargs={"re_files": filename}, args=(queue, filename))
def test_alive_doesnt_terminate(mocker): mock_start_process = mocker.patch('watchgod.main._start_process') mock_start_process.return_value = FakeProcess(exitcode=None) mock_kill = mocker.patch('watchgod.main.os.kill') assert run_process('/x/y/z', object(), watcher_cls=FakeWatcher, debounce=5, min_sleep=1) == 1 assert mock_start_process.call_count == 2 assert mock_kill.call_count == 2
def test_dead_callback(mocker): mock_start_process = mocker.patch('watchgod.main._start_process') mock_start_process.return_value = FakeProcess(is_alive=False) mock_kill = mocker.patch('watchgod.main.os.kill') c = mocker.MagicMock() assert run_process('/x/y/z', object(), watcher_cls=FakeWatcher, callback=c, debounce=5, min_sleep=1) == 1 assert mock_start_process.call_count == 2 assert mock_kill.call_count == 0 assert c.call_count == 1 c.assert_called_with({'x'})
import logging import os from wsgiref.simple_server import make_server def main(): import server with make_server('localhost', 8000, server.app) as httpd: logging.info("Server up at localhost:8000") httpd.serve_forever() if __name__ == '__main__': import watchgod class PythonConfigWatcher(watchgod.DefaultDirWatcher): ignored_dirs = watchgod.DefaultDirWatcher.ignored_dirs | {'venv'} def should_watch_file(self, entry): return entry.name.endswith(('.py', '.pyx', '.pyd', '.yaml')) watchgod.run_process(os.getcwd(), main, watcher_cls=PythonConfigWatcher)
def _main(): watcher = AllWatcher('/Users/johan/Dev/smash-rl') run_process(path='stats.json', target=plot_stuff, watcher_cls=watcher)
from watchgod import run_process import os def foobar(a, b, c): os.system("python3 app_with_python_only.py") # print(a,b,c) run_process('.', foobar, args=(1, 2, 3))
import os from watchgod import run_process def run(): import handlers import resource import seed from server import server server.run(host='0.0.0.0', port=os.getenv('PORT', 8080), workers=1) run_process('../server', run)
import configparser import os, signal from watchgod import watch, run_process import socket import multiprocessing #own-modules import from gateway import Gateway def getConfig(): configFile = configparser.ConfigParser() configFile.read("Gateway.config") config = {} config['WebPort'] = int(config['Configuration']['WebPort']) config['ListenerPort'] = int(configFile['Configuration']['ListenerPort']) config['ServerIP'] = str(configFile['Configuration']['ServerIP']) config['ServerPort'] = int(configFile['Configuration']['ServerPort']) config['VizrtEmptyScenePath'] = str(configFile['Configuration']['EmptyScenePath']) config['ServerType'] = str(configFile['Configuration']['ServerType']) config['ChannelportScenesDirectoryPath'] = str(configFile['Configuration']['ChannelportScenesDirectoryPath']) return config def runGateway(): config = getConfig() gw = Gateway(config) if __name__ == '__main__': multiprocessing.freeze_support() run_process("Gateway.config", runGateway)
ones.add((i, j)) return ones def life(): ones = input_read(filename) # ones = random_board() queue = collections.deque() while True: os.system("clear") board = draw_board(ones) print(board) if board in queue: return if len(queue) > 7: queue.popleft() queue.append(board) ones = iterate(ones) time.sleep(refresh_rate) filename = sys.argv[1] watchgod.run_process(filename, life)
def develop(): os.environ["LOGLEVEL"] = "DEBUG" current_dir = os.path.dirname(os.path.realpath(__file__)) run_process(os.path.join(current_dir, 'fluid_pad'), main)
import jacktrip_pypatcher as jtp import time import sys from watchgod import run_process def foobar(): while True: try: jtp.main() time.sleep(60) except Exception as e: print("pypatcher could not start:", e) sys.exit("Exited because of pypatcher error") run_process('/var/tmp/jacktrip_pypatcher', foobar)
# watch.py import subprocess from watchgod import run_process, AllWatcher def runner(): subprocess.run(['python', '-m', 'build_pop_n_fade']) if __name__ == '__main__': # by default, WatchGod only watches for changes in .py files; # this watches for everything (including SVG files). run_process('.', runner, watcher_cls=AllWatcher)