def _extract_pdf(): filename_initials = ''.join(c for c in str(Path(pdf_filename).name) if c.isupper()) if not filename_initials: filename_initials = pdf_filename[0] number_of_images = len(subprocess.check_output([ 'pdfimages', '-list', str(pdf_filename) ]).split(b'\n')) - 2 observer = Observer() event_handler = FileCreationHandler(expected_total=number_of_images) observer.schedule(event_handler, str(dst_folder_path), recursive=False) observer.setDaemon(True) observer.start() try: subprocess.call([ 'pdfimages', '-p', '-png', str(pdf_filename), str(dst_folder_path.joinpath(filename_initials)) ]) observer.stop() except KeyboardInterrupt: observer.stop() observer.join() event_handler.tqdm.close()
def watch_dir_for_change(dirs_to_watch, event_fn): event_handler = WatchdogHandler(event_fn) observer = Observer() for directory in dirs_to_watch: observer.schedule(event_handler, path=directory) observer.setDaemon(True) observer.start() return observer
def schedule_watch(self, path): # create a watch on the parent directory. try: observer = Observer() observer.schedule(InputMonitoring(), path=path, recursive=True) observer.setDaemon(True) observer.start() logger.info('user_message', msg=f'Started monitoring folder', path=path) except Exception as e: logger.error('admin_message', msg=f'Could not monitor input directory {path}', exc_info=e)
class Watcher(object): def __init__(self, env, output_path=None): self.env = env self.event_handler = EventHandler(env, output_path) self.observer = Observer() self.observer.schedule(self.event_handler, env.root_path, recursive=True) self.observer.setDaemon(True) def __iter__(self): while 1: try: yield self.event_handler.queue.get(timeout=1) except Queue.Empty: pass
class BasicWatcher(object): def __init__(self, paths, callback=None): self.event_handler = EventHandler(callback=callback) self.observer = Observer() for path in paths: self.observer.schedule(self.event_handler, path, recursive=True) self.observer.setDaemon(True) def is_interesting(self, time, event_type, path): return True def __iter__(self): if self.event_handler.queue is None: raise RuntimeError("watcher used with callback") while 1: try: item = self.event_handler.queue.get(timeout=1) if self.is_interesting(*item): yield item except _Empty: pass
def start_service(): event_handler = MyHandler() # print("\n\n----------\n\ninside start_service") # print watch_directory observer = Observer() observer.schedule(event_handler, watch_directory, True) observer.setDaemon(True) observer.start() """ Keep the script running or else python closes without stopping the observer thread and this causes an error. """ try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()
try: from watchdog.observers import Observer except ImportError: raise DelogXError('Import watchdog Failed') try: from flask import Flask from flask_babel import Babel except ImportError: raise DelogXError('Import Flask Failed') from DelogX.config import DelogXConfig as config from DelogX.api import DelogXAPI from DelogX.watch import BlogHandler if not os.path.exists(config.site_info['POST_DIR']): raise DelogXError(config.site_info['POST_DIR'] + ' Not Found') if not os.path.exists(config.site_info['PAGE_DIR']): raise DelogXError(config.site_info['PAGE_DIR'] + ' Not Found') observer = Observer() observer.setDaemon(True) observer.schedule(BlogHandler(patterns=['*.md']), config.site_info['POST_DIR']) observer.schedule(BlogHandler(patterns=['*.md']), config.site_info['PAGE_DIR']) observer.start() app = Flask(__name__, static_url_path='/static') babel = Babel(app) api = DelogXAPI(config.site_info) from DelogX import route
def serve(context: Context, port=8000, browsersync_port=3000, browsersync_ui_port=3030): """ Starts a development server with auto-building and live-reload """ try: from watchdog.observers import Observer except ImportError: context.pip_command('install', 'watchdog>0.8,<0.9') from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler class RebuildHandler(PatternMatchingEventHandler): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._patterns = ['*.js', '*.scss', '*.html'] self._ignore_directories = True self.builder = None self.rebuild_javascript = threading.Event() self.rebuild_stylesheets = threading.Event() def on_any_event(self, event): if self.builder: self.builder.cancel() extension = event.src_path.rsplit('.', 1)[-1].lower() if extension == 'js': self.rebuild_javascript.set() elif extension == 'scss': self.rebuild_stylesheets.set() self.builder = threading.Timer(3, self.rebuild) self.builder.start() def rebuild(self): if self.rebuild_javascript.is_set(): self.rebuild_javascript.clear() context.debug('Triggering javascript build') bundle_javascript(context) if self.rebuild_stylesheets.is_set(): self.rebuild_stylesheets.clear() context.debug('Triggering stylesheet build') bundle_stylesheets(context) context.debug('Reloading browsers') context.node_tool('browser-sync', 'reload', '--port=%s' % browsersync_port) context.info('Watching sources') observer = Observer() paths = [ context.app.common_asset_source_path, context.app.asset_source_path, context.app.common_templates_path, context.app.templates_path, ] handler = RebuildHandler() for path in paths: observer.schedule(handler, path, recursive=True) observer.setDaemon(True) observer.start() context.info('Starting browser sync') browsersync_args = ['start', '--host=localhost', '--no-open', '--logLevel', {0: 'silent', 1: 'info', 2: 'debug'}[context.verbosity], '--port=%s' % browsersync_port, '--proxy=localhost:%s' % port, '--ui-port=%s' % browsersync_ui_port] browsersync = functools.partial(context.node_tool, 'browser-sync', *browsersync_args) threading.Thread(target=browsersync, daemon=True).start() context.info('Starting web server') return start(context, port=port)