本文整理汇总了Python中watchdog.observers.Observer.stop方法的典型用法代码示例。如果您正苦于以下问题:Python Observer.stop方法的具体用法?Python Observer.stop怎么用?Python Observer.stop使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类watchdog.observers.Observer
的用法示例。
在下文中一共展示了Observer.stop方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: watch_directory
# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import stop [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()
示例2: mainLoop
# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import stop [as 别名]
def mainLoop(self):
logging.debug("Monitor: started main loop.")
self.session = self.dm.Session()
self.library = Library(self.dm.Session)
observer = Observer()
self.eventHandler = MonitorEventHandler(self)
for path in self.paths:
if os.path.exists(path):
observer.schedule(self.eventHandler, path, recursive=True)
observer.start()
while True:
try:
(msg, args) = self.queue.get(block=True, timeout=1)
except:
msg = None
#dispatch messages
if msg == "scan":
self.dofullScan(self.paths)
if msg == "events":
self.doEventProcessing(args)
#time.sleep(1)
if self.quit:
break
self.session.close()
self.session = None
observer.stop()
logging.debug("Monitor: stopped main loop.")
示例3: main
# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import stop [as 别名]
def main():
if (len(sys.argv) > 1 and os.path.exists(sys.argv[1]) and os.path.isfile(sys.argv[1])):
filename = sys.argv[1]
else:
filename = gui.get_path("*.csv",defaultFile="data.csv")
commonPath = os.path.abspath(os.path.split(filename)[0])
outputFile = os.path.join(commonPath, "odmanalysis.csv")
print "Now watching %s for changes" % filename
handler = OMDCsvChunkHandler(filename,outputFile)
observer = Observer()
observer.schedule(handler, path=commonPath, recursive=False)
handler.startPCChain()
observer.start()
try:
while True:
time.sleep(1)
except (KeyboardInterrupt, SystemExit):
print "Stopping..."
observer.stop()
time.sleep(1)
observer.join()
示例4: WatchFile
# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import stop [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
示例5: main
# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import stop [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)
示例6: __init__
# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import stop [as 别名]
def __init__(self, config):
"""
Initialize the watcher, use the config passed from main
"""
self.config = config
# List of pending files
self.pending_files = set()
self.sync_timer = None
# Setup our watchdog observer
observer = Observer()
observer.schedule(ChangeHandler(self.on_file_changed), path=config.directory, recursive=True)
observer.start()
logging.info("Starting change tracker, cmd: {}, dir: {}, delay: {}".format(config.sync_cmd,
config.directory,
config.delay))
try:
while True:
time.sleep(0.5)
except KeyboardInterrupt:
observer.stop()
observer.join()
示例7: __init__
# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import stop [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')
示例8: __init__
# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import stop [as 别名]
class Sceduler:
def __init__(self, config):
fs = config.get('scheduler', 'fs', 0)
dest = config.get('store', 'path', 0)
self.ioqueue = Queue()
self.iothread = Thread(target=self.ioprocess)
self.iothread.daemon = True
self.observer = Observer()
self.event_handler = IoTask(self.ioqueue, fs, dest)
self.observer.schedule(self.event_handler, fs, recursive=True)
def ioprocess(self):
while True:
t = self.ioqueue.get()
try:
t.process()
finally:
self.ioqueue.task_done()
def start(self):
self.observer.start()
self.iothread.start()
def stop(self):
self.observer.stop()
self.iothread.stop()
def join(self):
self.observer.join()
self.iothread.join()
示例9: __init__
# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import stop [as 别名]
def __init__(self, input_dir, templates_dir):
paths = [input_dir, templates_dir]
threads = []
try:
observer = Observer()
event_handler = WatchEventHandler()
for i in paths:
targetPath = str(i)
observer.schedule(event_handler, targetPath, recursive=True)
threads.append(observer)
observer.start()
signal_watch_init = signal('watch_init')
signal_watch_init.send(self)
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
wrangler._reporter.log("Stopping with grace and poise", "green")
observer.stop()
observer.join()
except:
return None
示例10: compile
# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import stop [as 别名]
def compile(self):
"""
Generate autodoc rst files from code docstrings and compile sphinx output
"""
if self.options.get('watch', False):
# If the watch folder is set, we will set up
# an observer using watchdog and re-compile on code change
from watchdog.observers import Observer
observer = Observer()
handler = CompileEventHandler(self)
observer.schedule(handler, path=self.doc_path, recursive=True)
observer.start()
print "Watching folder @ {} for changes.".format(self.doc_path)
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print "Stopping watch folder and Exiting."
observer.stop()
observer.join()
print "Goodbye"
else:
print "Compiling autodoc rst and sphinx files"
self._compile_all()
print "Files compiled. Goodbye"
示例11: main
# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import stop [as 别名]
def main():
arguments = docopt(__doc__, version='Storyline HTTP v0.1')
if arguments.get('--debug'):
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stderr)
logger.addHandler(handler)
app.config.from_object(__name__)
app.debug = arguments.get('--debug')
story_path = arguments.get('STORY_PATH', '.')
global plot
plot = storyfile.load_plot_from_path(story_path)
observer = Observer()
observer.schedule(LoggingEventHandler(), path=story_path, recursive=True)
observer.schedule(Reloader(story_path), path=story_path, recursive=True)
observer.start()
try:
app.run()
finally:
observer.stop()
observer.join()
示例12: main
# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import stop [as 别名]
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--after', help="a command to run after")
args = parser.parse_args()
py_event_handler = TouchFileEventHandler(
patterns=['*.py'],
touch_file='index.rst'
)
rst_event_handler = MakeEventHandler(
patterns=['*.rst'],
make_target='html',
after=args.after)
observer = Observer()
observer.schedule(py_event_handler, path='..', recursive=True)
observer.schedule(rst_event_handler, path='.', recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
示例13: serve
# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import stop [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()
示例14: filemonitor
# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import stop [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()
示例15: watch
# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import stop [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()