本文整理汇总了Python中watchdog.observers.Observer.join方法的典型用法代码示例。如果您正苦于以下问题:Python Observer.join方法的具体用法?Python Observer.join怎么用?Python Observer.join使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类watchdog.observers.Observer
的用法示例。
在下文中一共展示了Observer.join方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: watch
# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import join [as 别名]
def watch(path, callback):
header("Build Daemon")
if Observer is None:
error("You need to install Watchdog for supporting file system watchers")
# We need to pause the session to make room for other jasy executions
session.pause()
# Initialize file system observer
observer = Observer()
observer.schedule(JasyEventHandler(), ".", recursive=True)
observer.start()
info("Started file system watcher for %s... [PID=%s]", path, os.getpid())
info("Use 'ulimit -n 1024' to increase number of possible open files")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
info("Stopped file system watcher for %s...", path)
observer.join()
示例2: main
# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import join [as 别名]
def main():
global badExtensionCounter, failedFlag, pool, failedProcessCounter#, db
sql_setup() # Set-up SQL Database/check to see if exists
# Initiate File Path Handler
observer = Observer()
observer.schedule(MyHandler(), path=file_path, recursive=True)
observer.start()
cpuCount = multiprocessing.cpu_count() # Count all available CPU's
print "\nTotal CPU Count: %d"%(cpuCount)
pool = multiprocessing.Pool(4, worker,(processQueue,)) # Create 4 child processes to handle all queued elements
active = multiprocessing.active_children() # All active child processes
print "Total number of active child processes: %s\n"%(str(active))
try:
while True:
time.sleep(0.2)
except KeyboardInterrupt:
pool.terminate() # Stop all child processes
pool.join() # Join the processes with parent and terminate
active = multiprocessing.active_children() # All active child processes, list should be empty at this point.
print "\nTotal number of active child processes: %s\n"%(str(active))
shutdown() # Run shutdown sequence
observer.stop()
observer.join()
sys.exit(1)
示例3: watch
# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import join [as 别名]
def watch(self, source, write=True, package=None, run=False, force=False):
"""Watches a source and recompiles on change."""
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
def recompile(path):
if os.path.isfile(path) and os.path.splitext(path)[1] in code_exts:
self.compile_path(path, write, package, run, force)
class watcher(FileSystemEventHandler):
def on_modified(_, event):
recompile(event.src_path)
def on_created(_, event):
recompile(event.src_path)
source = fixpath(source)
self.console.show("Watching "+showpath(source)+" ...")
self.console.print("(press Ctrl-C to end)")
observer = Observer()
observer.schedule(watcher(), source, recursive=True)
observer.start()
try:
while True:
time.sleep(.1)
except KeyboardInterrupt:
pass
finally:
observer.stop()
observer.join()
示例4: __init__
# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import join [as 别名]
class PropMTimeWatcher:
def __init__(self, app_data_folder):
self._app_data_folder = app_data_folder
self._observer = Observer()
self.schedule()
def schedule(self):
pref = PropMTimePreferences(self._app_data_folder)
self._observer.unschedule_all()
for path, watcher in pref.get_all_paths().items():
if watcher:
if os.path.exists(path):
event_handler = ModHandler(path, self._app_data_folder)
log.info('scheduling watcher : %s' % path)
self._observer.schedule(event_handler, path=path, recursive=True)
else:
log.error('Error: "%s" does not exist.\n\nPlease edit the path.\n\nTo do this, click on the %s icon and select "Paths".' %
(path, __application_name__))
self._observer.start()
def request_exit(self):
self._observer.unschedule_all()
self._observer.stop()
self._observer.join(TIMEOUT)
if self._observer.isAlive():
log.error('observer still alive')
示例5: WatchFile
# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import join [as 别名]
class WatchFile(object):
def __init__(self, send_msg_func, *args, **kargs):
self.path = kargs['path'] if kargs.has_key('path') else '.'
self.suffix = kargs['suffix'] if kargs.has_key('suffix') else '*' # star represent any file
self.observer = Observer()
self.event_handler = MyFileMonitor(self.suffix, callback=self.get_data)
self.send_msg_func = send_msg_func
self.filename = self.zip_filename = ''
def run(self):
self.observer.schedule(self.event_handler, self.path, recursive=True)
self.observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
self.observer.stop()
self.observer.join()
def get_data(self, filename):
data = self._unpack(filename)
data = str(data)
print(data, type(data))
self.send_msg_func(data)
def _unpack(self, filename):
# first rename suffix to zip file
# may not work on linux
if system == 'Windows':
filename = filename[2:] if filename.startswith('.\\') else filename
filename = filename.lstrip()
new_name = filename.split('.')[0] + '.zip'
new_name = new_name[1:] if new_name.startswith('\\') else new_name
elif system == 'Linux':
new_name = filename
print('Old name:', filename, ' New name:', new_name)
self.filename = filename
self.zip_filename = new_name
# waiting for operating sys create the file
time.sleep(3)
os.rename(filename, new_name)
zip_file = zipfile.ZipFile(new_name, 'r')
json_data = ""
for name in zip_file.namelist():
if name == "project.json":
file = zip_file.open(name, 'r')
json_data = "".join(file.readlines())
# change filename back to .sb2
if new_name.endswith('.zip'):
os.rename(new_name, filename)
return self.get_cmd(json_data)
def get_cmd(self, json_data):
jsonfy_data = json.loads(json_data)
child = jsonfy_data['children'][0]
scripts = child['scripts']
return scripts
示例6: watch_assets
# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import join [as 别名]
def watch_assets(options):
"""
Watch for changes to asset files, and regenerate js/css
"""
# Don't watch assets when performing a dry run
if tasks.environment.dry_run:
return
observer = Observer()
CoffeeScriptWatcher().register(observer)
SassWatcher().register(observer)
XModuleSassWatcher().register(observer)
XModuleAssetsWatcher().register(observer)
print("Starting asset watcher...")
observer.start()
if not getattr(options, 'background', False):
# when running as a separate process, the main thread needs to loop
# in order to allow for shutdown by contrl-c
try:
while True:
observer.join(2)
except KeyboardInterrupt:
observer.stop()
print("\nStopped asset watcher.")
示例7: watch
# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import join [as 别名]
def watch(path, handler=None, debug=True):
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class Handler(FileSystemEventHandler):
def on_any_event(self, event):
if debug:
print "File {0}: {1}".format(event.event_type, event.src_path)
if not handler:
print "No handler specified"
return
handler(event.src_path, event.event_type)
event_handler = Handler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
示例8: serve
# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import join [as 别名]
def serve(site, director):
"""Run a simple web server that serve the output directory and watches for
changes to the site. When something is changed, it should be generated.
"""
# Override the log level to display some interactive messages with the
# user. With the dev server running, there's no sense in being silent.
logger.setLevel(logging.INFO)
# Start the watchdog.
event_handler = SiteHandler(director)
observer = Observer()
observer.schedule(event_handler, site.path, recursive=True)
observer.start()
# The simple HTTP server is pretty dumb and does not even take a path to
# serve. The only way to serve the right path is to change the directory.
outdir = director.outdir
os.chdir(outdir)
socketserver.TCPServer.allow_reuse_address = True
httpd = socketserver.TCPServer(('', PORT), SimpleHTTPRequestHandler)
logger.info(
_('Serving {outdir} at http://localhost:{port}/.'
'\nPress Ctrl-C to quit.').format(outdir=outdir, port=PORT))
try:
httpd.serve_forever()
except KeyboardInterrupt:
logger.info(_('\nBye.'))
observer.stop()
observer.join()
示例9: start_watchdog
# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import join [as 别名]
def start_watchdog():
event_handler = FileSystemEventHandler()
observer = Observer()
observer.schedule(event_handler, path='../watch')
observer.start()
log_handler = LoggingEventHandler()
log_observer = Observer()
log_observer.schedule(log_handler, path='../watch')
log_observer.start()
try:
logging.info("Watching Directory")
while True:
time.sleep(1)
except KeyboardInterrupt:
logging.info("Kill message sent. Aborting")
observer.stop()
log_observer.stop()
except:
logging.info("Unexpected error: %s" % sys.exc_info()[0])
observer.stop()
log_observer.stop()
# Send Email
msg = "Unexpected error: %s\nScript Failed. Please log in and restart manually" % sys.exc_info()[0]
for receiver in toaddrs:
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, receiver, msg)
server.quit()
observer.join()
log_observer.join()
示例10: watch_directory
# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import join [as 别名]
def watch_directory(watch_dir, target_dir, condition=None):
if condition:
condition.acquire()
watch_path = abspath(watch_dir)
logger.info('Watch path: %s' % watch_path)
target_path = abspath(target_dir)
logger.info('Target path: %s' % target_path)
handler = ModifiedHandler(watch_path, target_path)
obs = Observer()
obs.schedule(handler, watch_path, recursive=True)
obs.start()
if condition:
condition.notify()
condition.release()
try:
while True:
sleep(1)
except KeyboardInterrupt:
obs.stop()
obs.join()
示例11: filemonitor
# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import join [as 别名]
def filemonitor(topdir, mode, jfs):
errors = {}
def saferun(cmd, *args):
log.debug('running %s with args %s', cmd, args)
try:
return apply(cmd, args)
except Exception as e:
puts(colored.red('Ouch. Something\'s wrong with "%s":' % args[0]))
log.exception('SAFERUN: Got exception when processing %s', args)
errors.update( {args[0]:e} )
return False
if mode == 'archive':
event_handler = ArchiveEventHandler(jfs, topdir)
elif mode == 'sync':
event_handler = SyncEventHandler(jfs, topdir)
#event_handler = LoggingEventHandler()
elif mode == 'share':
event_handler = ShareEventHandler(jfs, topdir)
observer = Observer()
observer.schedule(event_handler, topdir, recursive=True)
observer.start()
try:
puts(colored.green('Starting JottaCloud monitor'))
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
puts(colored.red('JottaCloud monitor stopped'))
observer.join()
示例12: start
# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import join [as 别名]
def start(self):
# Watch the source files for changes
filewatch = Observer()
filewatch.schedule(FilewatchHandler(parent=self,
ignore_patterns=['*.swp', '*~']),
self.src_dir,
recursive=True)
# Clean shutdown on ctrl+c
def signal_handler(signal, frame):
print
print 'Shutting down...'
self.stop_server()
filewatch.stop()
signal.signal(signal.SIGINT, signal_handler)
self.rebuild()
self.start_server()
print 'Serving at port', self.port
print 'Serving files from', self.final_build_dir
print('Press Ctrl+C to stop')
filewatch.start()
signal.pause()
filewatch.join(5000)
示例13: go_watch
# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import join [as 别名]
def go_watch():
try:
print 'Start watching %s' % PATH_TO_WATCH
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
event_handler = LoggingEventHandler()
observer = Observer()
observer.schedule(event_handler, PATH_TO_WATCH, recursive=True)
observer.start()
event_handler.on_modified = sync_upload
event_handler.on_deleted = sync_upload_delete
event_handler.on_created = sync_upload_create
event_handler.on_moved = sync_upload_move
time_loop = 1
try:
while True:
time.sleep(1)
time_loop += 1
if not time_loop % AUTO_SYNC_TIME:
print 'Auto sync every %s second' % AUTO_SYNC_TIME
if not observer.event_queue.unfinished_tasks:
sync_download()
check_dir_deleted()
print 'Auto check downloaded file or folder'
check_dir_deleted()
except KeyboardInterrupt:
print 'End watching.'
observer.stop()
observer.join()
except Exception, e:
print '*' * 10
print e
print '*' * 10
return
示例14: main
# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import join [as 别名]
def main():
if len(sys.argv) < 4:
print "Usage: autorerun <directory_to_monitory> <pattern> <command> <command_args>"
return
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
directory = sys.argv[1]
pattern = sys.argv[2]
command = sys.argv[3:]
event_handler = RestartSubProcessEvent(command, pattern)
observer = Observer()
observer.schedule(event_handler, directory, recursive=True)
observer.start()
try:
while True:
time.sleep(0.1)
except KeyboardInterrupt:
observer.stop()
event_handler.kill()
observer.join()
示例15: main
# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import join [as 别名]
def main():
if not config['play']['scan']:
raise Exception('''
Nothing to scan. Add a path in the config file.
Example:
play:
scan:
-
type: shows
path: /a/path/to/the/shows
''')
obs = Observer()
for s in config['play']['scan']:
event_handler = Handler(
scan_path=s['path'],
type_=s['type'],
)
obs.schedule(
event_handler,
s['path'],
recursive=True,
)
obs.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
obs.stop()
obs.join()