当前位置: 首页>>代码示例>>Python>>正文


Python Observer.unschedule方法代码示例

本文整理汇总了Python中watchdog.observers.Observer.unschedule方法的典型用法代码示例。如果您正苦于以下问题:Python Observer.unschedule方法的具体用法?Python Observer.unschedule怎么用?Python Observer.unschedule使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在watchdog.observers.Observer的用法示例。


在下文中一共展示了Observer.unschedule方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: unschedule

# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import unschedule [as 别名]
 def unschedule(self, path):
     ''' 
     @summary: 監視リストから指定したファイルパスを監視するwatchを除去する
              整理はしていない
     @warning:  Linuxのみwatchスレッドが死んでいない テスト&要修正
     '''
     path = abspath(path)
     Observer.unschedule(self, self.watch_path[path])
     del self.watch_path[path]
     logger.debug("unschedule %s" % path)
开发者ID:bluele,项目名称:pystol,代码行数:12,代码来源:observer.py

示例2: main

# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import unschedule [as 别名]
	def main(self):
		eventos = Copiar_JDF_to()
		observador = Observer()
		observador.schedule(eventos, self.pasta_monitorada , recursive=False)
		observador.start()

		try:
			while True:
				time.sleep(1)
		except KeyboardInterrupt:
			observador.unschedule(eventos)
			observador.stop()
		observador.join()
		print ("FIM")
开发者ID:olivx,项目名称:scripts,代码行数:16,代码来源:monitor_tdb.py

示例3: main

# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import unschedule [as 别名]
def main():

    print('Starting vagrant rsync auto service.')

    #INITIALIZE
    vagrant('global-status', _bg=True, _out=vagrant_status_out).wait()
    last = time.time()

    handler = VagrantEventHandler()
    observer = Observer()
    watchers = {}

    #START WATCHING
    try:
        observer.start()
        while True:

            vagrant_dirs = set(vagrant_rsync_dirs.keys())
            watched_dirs = set(watchers.keys())

            for d in (vagrant_dirs - watched_dirs):
                watchers[d] = observer.schedule(handler, d, recursive=True)
                print('Observer is watching {}'.format(d))

            for d in (watched_dirs - vagrant_dirs):
                w = watchers.pop(d)
                observer.unschedule(w)
                print('Observer has stopped watching {}'.format(d))


            time.sleep(SLEEP_INTERVAL)
            passed = time.time() - last
            if passed > CHECK_INTERVAL:
                vagrant('global-status', _bg=True, _out=vagrant_status_out)
                last = time.time()

    #SHUT DOWN
    except KeyboardInterrupt:
        print(' << (*) >> ')
        observer.stop()

    observer.join()
    print('Goodbye :-)')
开发者ID:meantheory,项目名称:dotfiles,代码行数:45,代码来源:vra.py

示例4: Rainmaker

# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import unschedule [as 别名]
class Rainmaker():
   
    def __init__(self):
        self.event_handlers = {}
        self.observer = Observer()
        self.observer.start()

    def add_watch(self,watch_path,rec_flag=True):
        event_handler = RainmakerEventHandler( watch_path )
        self.event_handlers[watch_path] = event_handler
        self.observer.schedule( event_handler, watch_path, recursive = rec_flag) 
    
    def remove_watch(self, k): 
        eh = self.event_handlers.pop(k)
        self.observer.unschedule(eh)

    def shutdown(self):
        self.log.info( "Shutting down FSwatcher")
        self.observer.stop()
        self.observer.unschedule_all()
        self.observer.join()
开发者ID:hattwj,项目名称:rainmaker,代码行数:23,代码来源:_fsmon.py

示例5: reportRecursiveChanges

# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import unschedule [as 别名]
            if replica in triggered_reps:
                reportRecursiveChanges("", triggered_reps[replica])
                del triggered_reps[replica]
            sendCmd("DONE", [])
            _debug_triggers()
        elif cmd == "RESET":
            # Stop observing replica.
            [replica] = args
            if not replica in replicas:
                warn("unknown replica: " + replica)
                continue
            watch = replicas[replica]["watch"]
            if watch is not None:
                observer.unschedule(watch)
            del replicas[replica]
            if replica in triggered_reps:
                del triggered_reps[replica]
            _debug_triggers()
        else:
            sendError("unexpected root cmd: " + cmd)


if __name__ == '__main__':
    try:
        main()
    finally:
        for replica in replicas:
            observer.unschedule(replicas[replica]["watch"])
        observer.stop()
        observer.join()
开发者ID:hnsl,项目名称:unox,代码行数:32,代码来源:unox.py

示例6: __init__

# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import unschedule [as 别名]
class FileDaemon:
    def __init__(self, msg_identifier, send_config):
        #Attributes
        self.target_dir = send_config["PATH_BASE"]
        self._monitor_flag_ = threading.Event()
        self.watch = None

        #Components
        self._logger_ = EventLogger()
        self._event_handler_ = SyncEventHandler(msg_identifier, send_config)
        self._observer_ = Observer()

    """
        Public methods
    """
    def initialize(self):
        """
            Initializes components, starts logging
        """
        #Prep for monitor
        self._monitor_flag_.clear()

        #Initialize components
        logfile = os.path.dirname(self.target_dir[:-1]) + SLASH + "daemon.log"
        self._logger_.init_session(logfile)
        self._event_handler_.initialize()
        self._observer_.start()

    def start(self):
        """
            Starts/resumes observing a target directory. Wraps up the monitor method
            which is used as the target for a separate thread.
        """
        if self._monitor_flag_.is_set():
            return #Already running
        else:
            self._monitor_flag_.set()
            threading.Thread(target=self._monitor_).start()

    def full_sync(self):
        """
            Handle for the directory sync method of event_handler which
            allows controller to request a sync of entire directory
        """
        self._event_handler_.dir_sync(self.target_dir)

    def pause(self):
        """
            Pause observation with intent to resume
        """
        self._monitor_flag_.clear()

    def stop(self):
        """
            End observation with no intent to resume
        """
        self._monitor_flag_.clear()
        time.sleep(2) #Wait for local activity to settle
        self._observer_.stop() #stop observing
        self._observer_.join() #wait for all threads to be done

    def is_alive(self):
        return self._monitor_flag_.is_set()

    """
        Protected methods
    """
    def _monitor_(self):
        """
            Function run on separate thread which acts as parent to observer thread(s).
            Used to control operation flow of observer using monitor_flag
        """
        self._logger_.log("INFO","Scheduling observation of " + self.target_dir + " tree...")
        self.__watch__ = self._observer_.schedule(self._event_handler_, self.target_dir, recursive=True)
        while (self._monitor_flag_.is_set()):
            time.sleep(1)
        self._observer_.unschedule(self.__watch__)
开发者ID:wbkostan,项目名称:uvacs3240-g11,代码行数:79,代码来源:ServerFileDaemon.py

示例7: WatchdogTests

# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import unschedule [as 别名]

#.........这里部分代码省略.........
            local_file.write(new_string)
        while True:
            try:
                task = fake_queue.get(block=True, timeout=1)
            except queue.Empty:
                break
            self.assertEqual(task, fake_handle)

    # A Handler blocking on one event (ex: inserting into a busy queue)
    # should not prevent handling of further events
    def testHandlerHanging(self):
        class HangingHandler(EventHandler):
            def on_any_event(self, event):
                print("Handler hanging...")
                time.sleep(1)
                print("Handler dispatching")
                super().on_any_event(event)

        self.observer.remove_handler_for_watch(self.handler, self.watch)
        slow_handler = HangingHandler(self.events)
        self.observer.add_handler_for_watch(slow_handler, self.watch)
        for i in range(5):
            with open(os.path.join(TMP_DIR, "f"+str(i)), "w") as local_file:
                local_file.write("Write #"+str(i))
            time.sleep(0.1)
        time.sleep(6)
        num = len(empty_tasks(self.events))
        print("[Hanging] "+str(num)+" events")
        self.assertTrue(num >= 5)

    # Scheduling a new watch while another one is running
    # In this test, each write should set off 2 events (open+close) as seen on the next test
    # However watchdog is nice enough to avoid adding similar events to its internal queue
    def testNewScheduling(self):
        self.assertTrue(self.events.empty()) # Queue starts off
        with open(remote_dir + filename, "w") as remote_file:
            remote_file.write("Going once")
        self.assertRaises(queue.Empty, self.events.get, timeout=1) # No Handler is watching the file yet

        handler2 = EventHandler(self.events)
        self.observer.schedule(event_handler=handler2, path=remote_dir, recursive=True)

        with open(remote_dir + filename, "w") as remote_file:
            remote_file.write("Going twice")
        l1 = empty_tasks(self.events) # Now it should work
        self.assertEqual(len(l1), 1) # Single event
        for task in l1:
            self.assertEqual(task.src_path, remote_dir + filename)
            self.assertEqual(task.dest_path, local_dir + filename)

        with open(local_dir + filename, "w") as local_file:
            local_file.write("Going thrice") # Writing to the local file still works
        l2 = empty_tasks(self.events)
        self.assertEqual(len(l2), 1)  # Single event
        for task in l2:
            self.assertEqual(task.src_path, local_dir + filename)
            self.assertEqual(task.dest_path, remote_dir + filename)

    # It should be possible to remove a scheduled watch
    def testWatchRemoval(self):
        handler2 = EventHandler(self.events)
        watch2 = self.observer.schedule(event_handler=handler2, path=remote_dir, recursive=True)
        for client in [ {"path":local_dir+filename, "watch":self.watch},
                      {"path":remote_dir+filename, "watch":watch2} ]:
            with open(client["path"], "w") as file:
                file.write("This will make an event")
            time.sleep(0.5)
            task = self.events.get(timeout=1)
            self.assertEquals(task.src_path, client["path"])

            self.observer.unschedule(client["watch"])
            with open(local_dir+filename, "w") as local_file:
                local_file.write("This won't")
            self.assertRaises(queue.Empty, self.events.get, timeout=1)

    # Each open() and each close() should produce an event
    # They are sometimes squashed into a single event if done
    # Quickly enough (i.e. "with open(file) as f: f.write()")
    def testEventsPerWrite(self):
        local_file = open(local_dir+filename, "w")
        self.assertTrue(len(empty_tasks(self.events)) == 1) # Opening sets off an event
        local_file.write("First")
        self.assertTrue(len(empty_tasks(self.events)) == 0) # Writing doesn't set off an event
        local_file.write("Second")
        self.assertTrue(len(empty_tasks(self.events)) == 0) # Writing doesn't set off an event
        local_file.close()
        self.assertTrue(len(empty_tasks(self.events)) == 1) # Closing sets off an event

    def testEventsForBigFileCopy(self):
        self.observer.schedule(self.handler, TMP_DIR, recursive=True)
        try:
            os.mkdir(TMP_DIR)
        except FileExistsError:
            pass
        try:
            shutil.copy(BIG_FILE, BIG_IN)
        except OSError:
            self.fail()
        num = empty_tasks(self.events)
        print("Used "+str(len(num))+" events")
开发者ID:opprDev,项目名称:SimpleCloud,代码行数:104,代码来源:WatchdogTests.py

示例8: ModuleFileWatcher

# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import unschedule [as 别名]
class ModuleFileWatcher( EditorModule ):
	def __init__(self):
		super(ModuleFileWatcher, self).__init__()
		self.watches={}

	def getName(self):
		return 'filewatcher'

	def getDependency(self):
		return []

	def onLoad(self):		
		self.observer=Observer()
		self.observer.start()
		
		signals.connect( 'file.moved',    self.onFileMoved )
		signals.connect( 'file.added',    self.onFileCreated )
		signals.connect( 'file.removed',  self.onFileDeleted )
		signals.connect( 'file.modified', self.onFileModified )
		
	def onStart( self ):
		self.assetWatcher=self.startWatch(
			self.getProject().getAssetPath(),
			ignorePatterns = ['*/.git','*/.*','*/_gii']
		)
		
	def startWatch(self, path, **options):
		path = os.path.realpath(path)
		if self.watches.get(path):
			logging.warning( 'already watching: %s' % path )
			return self.watches[path]
		logging.info ( 'start watching: %s' % path )
		
		ignorePatterns = ['*/.git','*/.*','*/_gii'] + options.get('ignorePatterns',[])

		handler = FileWatcherEventHandler(
				options.get( 'patterns', None ),
				ignorePatterns,
				options.get( 'ignoreDirectories', False ),
				options.get( 'caseSensitive', True )
			)

		watch = self.observer.schedule( handler, path, options.get( 'recursive', True ) )
		self.watches[ path ] = watch
		return watch

	def onStop( self ):
		# print 'stop file watcher'
		self.observer.stop()
		self.observer.join( 0.5 )
		# print 'stopped file watcher'

	def stopWatch(self, path):
		path  = os.path.realpath(path)
		watch = self.watches.get(path, None)
		if not watch: return
		self.observer.unschedule(watch)
		self.watches[path] = None

	def stopAllWatches(self):
		# logging.info('stop all file watchers')
		self.observer.unschedule_all()
		self.watches = {}

	def onFileMoved(self, path, newpath):
		# print('asset moved:',path, newpath)
		app.getAssetLibrary().scheduleScanProject()
		pass

	def onFileCreated(self, path):
		# print('asset created:',path)
		app.getAssetLibrary().scheduleScanProject()
		pass

	def onFileModified(self, path):
		# print('asset modified:',path)
		app.getAssetLibrary().scheduleScanProject()
		pass

	def onFileDeleted(self, path):
		# print('asset deleted:',path)
		app.getAssetLibrary().scheduleScanProject()
		pass
开发者ID:pixpil,项目名称:gii,代码行数:85,代码来源:FileWatcher.py

示例9: INotify

# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import unschedule [as 别名]
class INotify(PollMixin):
    """
    I am a prototype INotify, made to work on Mac OS X (Darwin)
    using the Watchdog python library. This is actually a simplified subset
    of the twisted Linux INotify class because we do not utilize the watch mask
    and only implement the following methods:
     - watch
     - startReading
     - stopReading
     - wait_until_stopped
     - set_pending_delay
    """
    def __init__(self):
        self._pending_delay = 1.0
        self.recursive_includes_new_subdirectories = False
        self._callbacks = {}
        self._watches = {}
        self._state = NOT_STARTED
        self._observer = Observer(timeout=self._pending_delay)

    def set_pending_delay(self, delay):
        Message.log(message_type=u"watchdog:inotify:set-pending-delay", delay=delay)
        assert self._state != STARTED
        self._pending_delay = delay

    def startReading(self):
        with start_action(action_type=u"watchdog:inotify:start-reading"):
            assert self._state != STARTED
            try:
                # XXX twisted.internet.inotify doesn't require watches to
                # be set before startReading is called.
                # _assert(len(self._callbacks) != 0, "no watch set")
                self._observer.start()
                self._state = STARTED
            except:
                self._state = STOPPED
                raise

    def stopReading(self):
        with start_action(action_type=u"watchdog:inotify:stop-reading"):
            if self._state != STOPPED:
                self._state = STOPPING
            self._observer.unschedule_all()
            self._observer.stop()
            self._observer.join()
            self._state = STOPPED

    def wait_until_stopped(self):
        return self.poll(lambda: self._state == STOPPED)

    def _isWatched(self, path_u):
        return path_u in self._callbacks.keys()

    def ignore(self, path):
        path_u = path.path
        self._observer.unschedule(self._watches[path_u])
        del self._callbacks[path_u]
        del self._watches[path_u]

    def watch(self, path, mask=IN_WATCH_MASK, autoAdd=False, callbacks=None, recursive=False):
        precondition(isinstance(autoAdd, bool), autoAdd=autoAdd)
        precondition(isinstance(recursive, bool), recursive=recursive)
        assert autoAdd == False

        path_u = path.path
        if not isinstance(path_u, unicode):
            path_u = path_u.decode('utf-8')
            _assert(isinstance(path_u, unicode), path_u=path_u)

        if path_u not in self._callbacks.keys():
            self._callbacks[path_u] = callbacks or []
            self._watches[path_u] = self._observer.schedule(
                INotifyEventHandler(path_u, mask, self._callbacks[path_u], self._pending_delay),
                path=path_u,
                recursive=False,
            )
开发者ID:tahoe-lafs,项目名称:tahoe-lafs,代码行数:78,代码来源:inotify.py

示例10: ConfigWatcher

# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import unschedule [as 别名]
class ConfigWatcher(object):
    @staticmethod
    def get_config():
        config_name = 'config.ini'
        default_home = get_default_home()
        path = os.path.join(os.path.dirname(sys.executable), config_name)
        if os.path.exists(path):
            return path
        user_ini = os.path.expanduser(os.path.join(default_home, config_name))
        if os.path.exists(user_ini):
            return user_ini
        return None

    config_ini = get_config.__func__()

    class ConfigModifiedEventHandler(FileSystemEventHandler):
        def on_modified(self, event):
            if isinstance(event, FileModifiedEvent) and not event.is_directory and \
                            event.src_path == ConfigWatcher.config_ini:

                import ConfigParser
                config = ConfigParser.RawConfigParser()
                config.read(ConfigWatcher.config_ini)
                try:
                    new_upload_rate = config.getint(ConfigParser.DEFAULTSECT, 'upload-rate')
                except ConfigParser.NoOptionError as e:
                    new_upload_rate = -1

                try:
                    new_download_rate = config.getint(ConfigParser.DEFAULTSECT, 'download-rate')
                except ConfigParser.NoOptionError as e:
                    new_download_rate = -1
                self.set_rate_limit_changed(new_upload_rate, new_download_rate)

        @staticmethod
        def set_rate_limit_changed(new_upload_rate, new_download_rate): 
            try:
                current_upload_rate = int(Manager.get()._dao.get_config('upload_rate', -1))
            except ValueError:
                current_upload_rate = -1

            try:
                current_download_rate = int(Manager.get()._dao.get_config('download_rate', -1))
            except ValueError:
                current_download_rate = -1

            change = not (new_upload_rate == current_upload_rate and new_download_rate == current_download_rate)
            if not change:
                return

            slower = new_upload_rate < current_upload_rate or new_download_rate < current_download_rate
            if slower:
                # change processors first, then update the rate(s)
                ConfigWatcher.ConfigModifiedEventHandler.change_processors(new_upload_rate, new_download_rate)

            if new_upload_rate != current_upload_rate:
                BaseAutomationClient.set_upload_rate_limit(new_upload_rate)
                Manager.get()._dao.update_config('upload_rate', new_upload_rate)
                log.trace('update upload rate: %s', str(BaseAutomationClient.upload_token_bucket))

            if new_download_rate != current_download_rate:
                BaseAutomationClient.set_download_rate_limit(new_download_rate)
                Manager.get()._dao.update_config('download_rate', new_download_rate)
                log.trace('update download rate: %s', str(BaseAutomationClient.download_token_bucket))

            if change and new_upload_rate > current_upload_rate and new_download_rate > current_download_rate:
                # changed rate(s) first, then change processors
                ConfigWatcher.ConfigModifiedEventHandler.change_processors(new_upload_rate, new_download_rate)

        @staticmethod
        def change_processors(upload_rate, download_rate):
            max_processors = get_number_of_processors(upload_rate, download_rate)
            for engine in Manager.get().get_engines().values():
                try:
                    engine.get_queue_manager().restart(max_processors)
                    log.trace('update engine %s processors: %d local, %d remote, %d generic',
                              engine.get_uid(), max_processors[0], max_processors[1], max_processors[2])
                except Exception as e:
                    log.error('failed to update engine %s processors: %s', engine.get_uid(), str(e))

    def __init__(self):
        self.watch = None
        self.observer = Observer()

    def setup_watchdog(self):
        if not ConfigWatcher.config_ini:
            return
        event_handler = ConfigWatcher.ConfigModifiedEventHandler()
        self.watch = self.observer.schedule(event_handler, os.path.dirname(ConfigWatcher.config_ini), recursive=False)
        self.observer.start()

    def unset_watcher(self):
        self.observer.unschedule(self.watch)
开发者ID:mconstantin,项目名称:nuxeo-drive,代码行数:95,代码来源:manager.py

示例11: CollectionScanner

# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import unschedule [as 别名]
class CollectionScanner(object):
    def __init__(self):

        self.fswatcher = CollectionEventHandler(self)
        self.observer = Observer()
        self.watches = {}
        self.scanner_pool = Pool(processes=4)

        signal.signal(signal.SIGINT, self.quit)
        signal.signal(signal.SIGTERM, self.quit)

    def scan_directory(self, directory, full_scan):
        self.scanner_pool.apply_async(start_scanrunner, [directory, full_scan, self.last_shutdown_time])

    def add_directory(self, directory, full_scan=False):
        # start a full scan if required
        # otherwise do an incremental
        # and schedule a watch.

        self.scan_directory(directory, full_scan)
        #start_scanrunner(directory, full_scan, self.last_shutdown_time)
        #TODO(nikhil) fix me
        self.watches[directory] = True
        self.watches[directory] = self.observer.schedule(self.fswatcher, path=directory, recursive=True)

    def remove_directory(self, directory):
        try:
            self.observer.unschedule(self.watches[directory])
            del self.watches[directory]
        except KeyError:
            pass
        # also remove all tracks within that directory from DB
        tracks = Track.select(Track.q.url.startswith('file://'+directory))
        for track in tracks:
            track.destroySelf()

    def configuration_changed(self):
        # check if collection dirs have
        # been changed since we last started
        # if yes, we will do a full rescan
        # otherwise, an incremental scan.

        config = GlobalConfig()
        paths_saved_at = 0
        last_scan = 0
        self.last_shutdown_time = 0
        try:
            paths_saved_at = int(config['collection']['paths_saved_at'])
        except KeyError:
#TODO(nikhil) test this behaviour
            pass

        try:
            last_scan = int(config['collection']['last_scan'])
        except KeyError:
            last_scan = paths_saved_at - 1

        try:
            self.last_shutdown_time = int(config['last_shutdown_time'])
        except KeyError:
            pass

        collection_directories = set()
        try:
            collection_directories = set(config['collection']['paths'])
        except KeyError:
            pass

        full_scan = False
        if last_scan < paths_saved_at:
            full_scan = True

        if full_scan:
            try:
                # for a full scan, first wipe all tables
                Artist.deleteMany(None)
                Album.deleteMany(None)
                Genre.deleteMany(None)
                Composer.deleteMany(None)
                Track.deleteMany(None)
                TrackStatistics.deleteMany(None)
                AlbumStatistics.deleteMany(None)
                ArtistStatistics.deleteMany(None)
                GenreStatistics.deleteMany(None)
            except OperationalError:
                pass

        # first remove watches on
        # any directories that have been
        # removed from the collection directories
        existing_directories = set(self.watches.keys())
        for dir in existing_directories.difference(collection_directories):
            self.remove_directory(dir)

        for dir in collection_directories:
            if dir in self.watches:
                # directory is already being watched
                # do nothing
                pass
            else:
#.........这里部分代码省略.........
开发者ID:nikhilm,项目名称:muzicast,代码行数:103,代码来源:__init__.py

示例12: GoSyncModel

# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import unschedule [as 别名]

#.........这里部分代码省略.........

                f.close()
            except:
                raise ConfigLoadFailed()
        except:
            raise ConfigLoadFailed()

    def SaveConfig(self):
        f = open(self.config_file, 'w')
        f.truncate()
        if not self.sync_selection:
            self.config_dict['Sync Selection'] = [['root', '']]

        self.account_dict[self.user_email] = self.config_dict

        json.dump(self.account_dict, f)
        f.close()

    def DoAuthenticate(self):
        try:
            self.authToken = GoogleAuth(self.settings_file)
            self.authToken.LocalWebserverAuth()
            self.drive = GoogleDrive(self.authToken)
            self.is_logged_in = True
        except:
            dial = wx.MessageDialog(None, "Authentication Rejected!\n",
                                    'Information', wx.ID_OK | wx.ICON_EXCLAMATION)
            dial.ShowModal()
            self.is_logged_in = False
            pass

    def DoUnAuthenticate(self):
            self.do_sync = False
            self.observer.unschedule(self.iobserv_handle)
            self.iobserv_handle = None
            os.remove(self.credential_file)
            self.is_logged_in = False

    def DriveInfo(self):
        return self.about_drive

    def PathLeaf(self, path):
        head, tail = ntpath.split(path)
        return tail or ntpath.basename(head)

    def GetFolderOnDrive(self, folder_name, parent='root'):
        """
        Return the folder with name in "folder_name" in the parent folder
        mentioned in parent.
        """
        self.logger.debug("GetFolderOnDrive: searching %s on %s... " % (folder_name, parent))
        file_list = self.drive.ListFile({'q': "'%s' in parents and trashed=false" % parent}).GetList()
        for f in file_list:
            if f['title'] == folder_name and f['mimeType']=='application/vnd.google-apps.folder':
                self.logger.debug("Found!\n")
                return f

        return None

    def LocateFolderOnDrive(self, folder_path):
        """
        Locate and return the directory in the path. The complete path
        is walked and the last directory is returned. An exception is raised
        if the path walking fails at any stage.
        """
        dir_list = folder_path.split(os.sep)
开发者ID:hschauhan,项目名称:gosync,代码行数:70,代码来源:GoSyncModel.py

示例13: Rainmaker

# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import unschedule [as 别名]
class Rainmaker():
   
    def __init__(self,config=None, auto_start=True ):
        self.log=logging.getLogger('main')
        self.event_handlers = []
        self.config = config if config else  RainmakerConfig()
        self.profiles = self.config.profiles

        self.msg_q = Queue()
        self.observer = Observer()
        self.observer.start()

        if not auto_start:
            return

        for k in self.profiles:
            if self.profiles[k]['auto_start']==True:
                self.add_watch(k)

        if not self.event_handlers:            
            self.log.warn('No running profiles')

    def add_watch(self,key):
        if not key in self.profiles:
            self.log.error('unknown profile %s' % key)

        self.log.info('Starting profile: %s' % key)
        profile = self.profiles[key]

        profile['local_root'] = os.path.abspath(os.path.expanduser(profile['local_root']))
        
        profile.subst_all()

        if not os.path.isdir(profile['local_root']):
            self.log.info('creating dir: %s' % profile['local_root'])
            os.mkdir(profile['local_root'])
        patterns=['*.unison.tmp']     
        event_handler = RainmakerEventHandler()
        event_handler.init2( self.config, profile, self.msg_q, key )
        self.event_handlers.append( event_handler )

        rec_flag = True
        if profile.has_key('recursive'):
            rec_flag = bool(profile['recursive']) 
        self.observer.schedule( event_handler, profile['local_root'], recursive = rec_flag) 
        
        logging.info('Started profile: %s' % key)
    
        if profile['cmds']['startup'] != '':
            event_handler.startup_cmd()

    def remove_watch(self, k): 
        for eh in self.event_handlers:
            if eh.name == k:
                self.log.info('Stopping profile: %s' % k)
                self.observer.unschedule(eh)
                break 

    def messages(self):
        messages = []
        try:
            while True:
                messages.append( self.msg_q.get_nowait() )
        except Empty:
            pass

        return messages

    def shutdown(self):
        self.log.info( "Shutting down FSwatcher")
        self.observer.stop()
        self.observer.unschedule_all()
        self.observer.join()
        self.log.info("Shutting down thread and Fork pool")
        for eh in self.event_handlers:
            self.log.info('Stopping profile: %s' % eh.name)
            eh.stop()
开发者ID:hattwj,项目名称:rainmaker,代码行数:79,代码来源:_fsmon.py

示例14: ChangesWatcher

# 需要导入模块: from watchdog.observers import Observer [as 别名]
# 或者: from watchdog.observers.Observer import unschedule [as 别名]
class ChangesWatcher(FileSystemEventHandler):
    def __init__(self, application):
        self.task_map = {}  # path: ChangesKeeper
        self.application = application
        self.observer = Observer()
        self.changes = []
        self.changes_timer = None
        self.observer.start()

    def add_watch(self, path, mute_list=None):
        if path in self.task_map:
            return False
        else:
            mute_list = (mute_list or []) + DEFAULT_MUTE_LIST
            keeper = ChangesKeeper(path, mute_list)
            self.task_map[path] = keeper
            if os.path.exists(path):
                self.observer.schedule(self, path, recursive=True)
                return True
            return False

    def remove_watch(self, path):
        if path in self.task_map:
            keeper = self.task_map[path]
            watch = keeper.watch
            self.observer.unschedule(watch)
            return True
        else:
            return False

    def get_changes_since(self, timestamp, parent_path=None):
        ret = []
        for change in self.changes:
            if change.timestamp > timestamp and (not parent_path or path_is_parent(parent_path, change.path)):
                ret.append(change)
        return ret

    def add_pure_change(self, change):
        """ 监测change的类型,并添加非垃圾change和不在黑名单中的change
        """

        # 如果是黑名单及黑名单子目录的change,则跳过
        for mute_list in [keeper.mute_list for keeper in self.task_map.values()]:
            for mute_path in mute_list:
                if path_is_parent(mute_path, change.path):
                    print '...', change.type, change.path
                    return

        # 寻找当前change对应的垃圾change,找到后删除;未找到则添加当前change
        trash_changes = self.find_related_trash_changes(change)
        if trash_changes:
            for change in trash_changes:
                self.changes.remove(change)
                print '-  ', change.type, change.path
        else:
            self.changes.append(change)
            print '+  ', change.type, change.path
            self.compile_if_needed(change)

        ioloop.IOLoop.instance().add_callback(lambda: self.remove_outdated_changes(30))

    def compile_if_needed(self, change):
        if change.type == EVENT_TYPE_DELETED:
            return

        input_path = normalize_path(change.path)
        base_path, ext = os.path.splitext(input_path)
        ext = ext.lower()
        if ext not in['.less', '.coffee']:
            return

        project = self.application.find_project(input_path)
        if not project:
            return

        os.chdir(APP_FOLDER)
        begin_time = time.time()
        if ext == '.less':
            if project.compileLess:
                output_path = base_path + '.css'
                run_cmd('%s bundled/less/bin/lessc %s %s' % (NODE_BIN_PATH, input_path, output_path))
                print '.less ->- .css', change.path, time.time() - begin_time, 'seconds'
            else:
                print '.less -X- .css', change.path, '(OFF by settings)'

        elif ext == '.coffee':
            if project.compileCoffee:
                run_cmd('%s bundled/coffee/bin/coffee --compile %s' % (NODE_BIN_PATH, input_path))
                print '.coffee ->- .js', change.path, time.time() - begin_time, 'seconds'
            else:
                print '.coffee -X- .js', change.path, '(OFF by settings)'

    def check_folder_change(self, folder_path):
        if sys.platform.startswith('win') or \
                not os.path.isdir(folder_path):
            return

        now = time.time() - 0.5  # 0.5秒内的都算修改
        for filename in os.listdir(folder_path):
            file_path = os.path.join(folder_path, filename)
#.........这里部分代码省略.........
开发者ID:Megasu,项目名称:PyF5,代码行数:103,代码来源:watcher.py


注:本文中的watchdog.observers.Observer.unschedule方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。