a ]l=b°[ã@sðdZGdd„deƒZGdd„deƒZddlZejdkr@eejƒ‚ddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlmZdd lmZmZddlZddlZddlZddlZddlZddlZzdd lmZWneyþYn0zddlZddlZWney,dZYn0z ddl Z WneyRdZ Yn0d Z!d Z"d a#Gdd„deƒZ$Gdd„dƒZ%Gdd„de%ƒZ&Gdd„de%ƒZ'dd„Z(e(ƒZ)Gdd„dƒZ*dD]Z+e*e+ƒe,ƒe+<q¾Gdd„dƒZ-ie-_.ie-_/e-j0 1¡D]J\Z2Z3e4e-e2e3ƒe-j. 5e3¡e3 1¡D]\Z6Z7e7e,ƒe6<e6e-j/e7<q qøedd„e-j8 9¡ƒZ:e:e-j.d<de-j/e:<Gd d!„d!ƒZ;Gd"d#„d#e;ƒZGd(d)„d)ƒZ?Gd*d+„d+e?ƒZ@Gd,d-„d-e?ƒZAGd.d/„d/eAƒZBGd0d1„d1eAƒZCGd2d3„d3eAƒZDGd4d5„d5eƒZEGd6d7„d7ƒZFGd8d9„d9ejGeFƒZHGd:d;„d;ejIeFƒZJGdd?„d?eFƒZLGd@dA„dAƒZMGdBdC„dCƒZNGdDdE„dEeƒZOGdFdG„dGƒZPGdHdI„dIƒZQeQƒaRGdJdK„dKeQƒZSdLdM„ZTdNdO„ZUeVdPkrìeUƒdS)QzW pyinotify @author: Sebastien Martini @license: MIT License @contact: seb@dbzteam.org c@seZdZdZdS)ÚPyinotifyErrorz1Indicates exceptions raised by a Pyinotify class.N)Ú__name__Ú __module__Ú __qualname__Ú__doc__©rrú-/usr/lib/python3.9/site-packages/pyinotify.pyrsrc@seZdZdZdd„ZdS)ÚUnsupportedPythonVersionErrorz0 Raised on unsupported Python versions. cCst |d|¡dS)zV @param version: Current Python version @type version: string z6Python %s is unsupported, requires at least Python 3.0N©rÚ__init__)ÚselfÚversionrrrr (s ÿÿz&UnsupportedPythonVersionError.__init__N©rrrrr rrrrr$sréN)ér)Údeque)ÚdatetimeÚ timedelta)Úreducez#seb@dbzteam.org (Sebastien Martini)z0.9.6Fc@seZdZdZdd„ZdS)ÚInotifyBindingNotFoundErrorz; Raised when no inotify support couldn't be found. cCsd}t ||¡dS)Nz!Couldn't find any inotify bindingr ©r Úerrrrrr lsz$InotifyBindingNotFoundError.__init__Nr rrrrrhsrc@sDeZdZdZedd„ƒZdd„Zdd„Zdd „Zd d „Z d d „Z dS)ÚINotifyWrapperz_ Abstract class wrapping access to inotify's functions. This is an internal class. cCs0trtƒ}| ¡r|Str,tƒ}| ¡r,|SdS)zO Factory method instanciating and returning the right wrapper. N)ÚctypesÚ_CtypesLibcINotifyWrapperÚinitÚinotify_syscallsÚ_INotifySyscallsWrapper)ÚinotifyrrrÚcreatevszINotifyWrapper.createcCs| ¡S)z< Return None is no errno code is available. )Ú _get_errno©r rrrÚ get_errno†szINotifyWrapper.get_errnocCs,| ¡}|durdSdt |¡tj|fS)NzErrno: no errno supportz Errno=%s (%s))r!ÚosÚstrerrorÚerrnoÚ errorcode)r ÚcoderrrÚ str_errnoŒszINotifyWrapper.str_errnocCs| ¡S©N)Ú _inotify_initr rrrÚ inotify_init’szINotifyWrapper.inotify_initcCst|tƒsJ‚| |||¡Sr()Ú isinstanceÚstrÚ_inotify_add_watch©r ÚfdÚpathnameÚmaskrrrÚinotify_add_watch•sz INotifyWrapper.inotify_add_watchcCs | ||¡Sr()Ú_inotify_rm_watch©r r/ÚwdrrrÚinotify_rm_watch›szINotifyWrapper.inotify_rm_watchN) rrrrÚ staticmethodrr!r'r*r2r6rrrrrqs rc@s<eZdZdd„Zdd„Zdd„Zdd„Zd d „Zd d „Zd S)rcCs d|_dSr(©Ú _last_errnor rrrr  sz _INotifySyscallsWrapper.__init__cCs tsJ‚dS)NT)rr rrrr¤sz_INotifySyscallsWrapper.initcCs|jSr(r8r rrrr¨sz"_INotifySyscallsWrapper._get_errnoc Cs@z t ¡}Wn.ty:}z|j|_WYd}~dSd}~00|S©Néÿÿÿÿ)rr*ÚIOErrorr$r9)r r/rrrrr)«s  z%_INotifySyscallsWrapper._inotify_initc CsFzt |||¡}Wn.ty@}z|j|_WYd}~dSd}~00|Sr:)rr2r<r$r9)r r/r0r1r5rrrrr-³s z*_INotifySyscallsWrapper._inotify_add_watchc CsDzt ||¡}Wn.ty>}z|j|_WYd}~dSd}~00|Sr:)rr6r<r$r9)r r/r5Úretrrrrr3»s z)_INotifySyscallsWrapper._inotify_rm_watchN© rrrr rrr)r-r3rrrrrŸs rc@s<eZdZdd„Zdd„Zdd„Zdd„Zd d „Zd d „Zd S)rcCsd|_d|_dSr()Ú_libcÚ_get_errno_funcr rrrr Åsz"_CtypesLibcINotifyWrapper.__init__c CsâtsJ‚d}tj d¡rd}d}ztj |¡}WnttfyFYn0tj|dd|_ tj |_ t |j dƒr„t |j dƒr„t |j dƒsˆd Sg|j j _tj|j j _tjtjtjg|j j_tj|j j_tjtjg|j j_tj|j j_dS) NÚcZfreebsdrT)Z use_errnor*r2r6F)rÚsysÚplatformÚ startswithÚutilZ find_libraryÚOSErrorr<ZCDLLr?r!r@Úhasattrr*ÚargtypesZc_intZrestypeZc_char_pZc_uint32r2r6)r Z try_libc_nameZ libc_namerrrrÉs4   ÿ þ  ÿ   z_CtypesLibcINotifyWrapper.initcCs|js J‚| ¡Sr()r@r rrrrès z$_CtypesLibcINotifyWrapper._get_errnocCs|jdusJ‚|j ¡Sr()r?r*r rrrr)ìsz'_CtypesLibcINotifyWrapper._inotify_initcCs6|jdusJ‚| t ¡¡}t |¡}|j |||¡Sr()r?ÚencoderBÚgetfilesystemencodingrZcreate_string_bufferr2r.rrrr-ðs z,_CtypesLibcINotifyWrapper._inotify_add_watchcCs|jdusJ‚|j ||¡Sr()r?r6r4rrrr3úsz+_CtypesLibcINotifyWrapper._inotify_rm_watchNr>rrrrrÄs  rcCs:t d¡}t ¡}| t d¡¡| |¡| d¡|S)zInitialize logger instance.Ú pyinotifyz0[%(asctime)s %(name)s %(levelname)s] %(message)sé)ÚloggingZ getLoggerZ StreamHandlerZ setFormatterZ FormatterZ addHandlerÚsetLevel)ÚlogZconsole_handlerrrrÚ logger_inits ÿ  rPc@s:eZdZdZdd„Zdd„Zdd„ZeeeƒZdd „Z d S) Ú ProcINotifya/ Access (read, write) inotify's variables through /proc/sys/. Note that usually it requires administrator rights to update them. Examples: - Read max_queued_events attribute: myvar = max_queued_events.value - Update max_queued_events attribute: max_queued_events.value = 42 cCsd|_||_dS)Nz/proc/sys/fs/inotify)Ú_baseÚ_attr)r Úattrrrrr szProcINotify.__init__cCsHttj |j|j¡dƒ}t| ¡ƒWdƒS1s:0YdS)z¨ Gets attribute's value. @return: stored value. @rtype: int @raise IOError: if corresponding file in /proc/sys cannot be read. ÚrN)Úopenr"ÚpathÚjoinrRrSÚintÚreadline)r Úfile_objrrrÚget_valszProcINotify.get_valcCsNttj |j|j¡dƒ"}| t|ƒd¡Wdƒn1s@0YdS)zÉ Sets new attribute's value. @param nval: replaces current value by nval. @type nval: int @raise IOError: if corresponding file in /proc/sys cannot be written. ÚwÚ N)rVr"rWrXrRrSÚwriter,)r Únvalr[rrrÚset_val&szProcINotify.set_valcCsd|j| ¡fS)Nz<%s=%d>)rSr\r rrrÚ__repr__3szProcINotify.__repr__N) rrrrr r\raÚpropertyÚvaluerbrrrrrQs   rQ)Zmax_queued_eventsZmax_user_instancesZmax_user_watchesc @s\eZdZdZdddddddd d d d d dœ ddddœdddddddœdœZdd„ZeeƒZdS)Ú EventsCodesaá Set of codes corresponding to each kind of events. Some of these flags are used to communicate with inotify, whereas the others are sent to userspace by inotify notifying some events. @cvar IN_ACCESS: File was accessed. @type IN_ACCESS: int @cvar IN_MODIFY: File was modified. @type IN_MODIFY: int @cvar IN_ATTRIB: Metadata changed. @type IN_ATTRIB: int @cvar IN_CLOSE_WRITE: Writtable file was closed. @type IN_CLOSE_WRITE: int @cvar IN_CLOSE_NOWRITE: Unwrittable file closed. @type IN_CLOSE_NOWRITE: int @cvar IN_OPEN: File was opened. @type IN_OPEN: int @cvar IN_MOVED_FROM: File was moved from X. @type IN_MOVED_FROM: int @cvar IN_MOVED_TO: File was moved to Y. @type IN_MOVED_TO: int @cvar IN_CREATE: Subfile was created. @type IN_CREATE: int @cvar IN_DELETE: Subfile was deleted. @type IN_DELETE: int @cvar IN_DELETE_SELF: Self (watched item itself) was deleted. @type IN_DELETE_SELF: int @cvar IN_MOVE_SELF: Self (watched item itself) was moved. @type IN_MOVE_SELF: int @cvar IN_UNMOUNT: Backing fs was unmounted. @type IN_UNMOUNT: int @cvar IN_Q_OVERFLOW: Event queued overflowed. @type IN_Q_OVERFLOW: int @cvar IN_IGNORED: File was ignored. @type IN_IGNORED: int @cvar IN_ONLYDIR: only watch the path if it is a directory (new in kernel 2.6.15). @type IN_ONLYDIR: int @cvar IN_DONT_FOLLOW: don't follow a symlink (new in kernel 2.6.15). IN_ONLYDIR we can make sure that we don't watch the target of symlinks. @type IN_DONT_FOLLOW: int @cvar IN_EXCL_UNLINK: Events are not generated for children after they have been unlinked from the watched directory. (new in kernel 2.6.36). @type IN_EXCL_UNLINK: int @cvar IN_MASK_ADD: add to the mask of an already existing watch (new in kernel 2.6.14). @type IN_MASK_ADD: int @cvar IN_ISDIR: Event occurred against dir. @type IN_ISDIR: int @cvar IN_ONESHOT: Only send event once. @type IN_ONESHOT: int @cvar ALL_EVENTS: Alias for considering all of the events. @type ALL_EVENTS: int éééééé é@é€éiii) Z IN_ACCESSZ IN_MODIFYZ IN_ATTRIBZIN_CLOSE_WRITEZIN_CLOSE_NOWRITEZIN_OPENZ IN_MOVED_FROMZ IN_MOVED_TOÚ IN_CREATEÚ IN_DELETEÚIN_DELETE_SELFÚ IN_MOVE_SELFi i@i€)Z IN_UNMOUNTÚ IN_Q_OVERFLOWÚ IN_IGNOREDiiii i@l)Z IN_ONLYDIRZIN_DONT_FOLLOWZIN_EXCL_UNLINKZ IN_MASK_ADDÚIN_ISDIRZ IN_ONESHOT)ÚOP_FLAGSZ EVENT_FLAGSZ SPECIAL_FLAGScCs*|}d}|t@r|t}d}|tj|S)a> Returns the event name associated to mask. IN_ISDIR is appended to the result when appropriate. Note: only one event is returned, because only one event can be raised at a given time. @param mask: mask. @type mask: int @return: event name. @rtype: str z%sz %s|IN_ISDIR)rureÚ ALL_VALUES)r1ÚmsÚnamerrrÚmaskname¡s zEventsCodes.masknameN)rrrrÚFLAG_COLLECTIONSrzr7rrrrreDs8=óýøì recCs||BSr(r)ÚxÚyrrrÚÉór~Ú ALL_EVENTSc@s(eZdZdZdd„Zdd„Zdd„ZdS) Ú_Eventzw Event structure, represent events raised by the system. This is the base class and should be subclassed. cCs"| ¡D]}t|g|¢RŽqdS)z‹ Attach attributes (contained in dict_) to self. @param dict_: Set of attributes. @type dict_: dictionary N)ÚitemsÚsetattr)r Údict_Ztplrrrr Ôs z_Event.__init__cCs¨d}t|j ¡dd„dD]b\}}| d¡r.q|dkrFtt||ƒƒ}nt|tƒrX|sXd}|dt  |¡t  d ¡t  |¡f7}qd t  d ¡t  |j j¡|t  d ¡f}|S) zS @return: Generic event string representation. @rtype: str ÚcSs|dS©Nrr©r|rrrr~ärz!_Event.__repr__..©ÚkeyÚ_r1z''z %s%s%sú=z %s%s%s %sú<ú>)ÚsortedÚ__dict__r‚rDÚhexÚgetattrr+r,Ú output_formatÚ field_nameÚ punctuationÚ field_valueÚ class_nameÚ __class__r)r ÚsrTrdrrrrbÞs$  þ   ýz_Event.__repr__cCst|ƒSr()Úreprr rrrÚ__str__õsz_Event.__str__N)rrrrr rbršrrrrrÎs rc@s eZdZdZdd„Zdd„ZdS)Ú _RawEventzm Raw event, it contains only the informations provided by the system. It doesn't infer anything. cCs8d|_|||| d¡dœ}t ||¡t t|ƒ¡dS)aï @param wd: Watch Descriptor. @type wd: int @param mask: Bitmask of events. @type mask: int @param cookie: Cookie. @type cookie: int @param name: Basename of the file or directory against which the event was raised in case where the watched directory is the parent directory. None if the event was raised on the watched item itself. @type name: string or None Nú)r5r1Úcookiery)Ú_strÚrstriprr rOÚdebugr,)r r5r1rryÚdrrrr þsý z_RawEvent.__init__cCs|jdurt |¡|_|jSr()ržrršr rrrršs  z_RawEvent.__str__N)rrrrr ršrrrrr›ùsr›c@seZdZdZdd„ZdS)ÚEventaÙ This class contains all the useful informations about the observed event. However, the presence of each field is not guaranteed and depends on the type of event. In effect, some fields are irrelevant for some kind of event (for example 'cookie' is meaningless for IN_CREATE whereas it is mandatory for IN_MOVE_TO). The possible fields are: - wd (int): Watch Descriptor. - mask (int): Mask. - maskname (str): Readable event name. - path (str): path of the file or directory being watched. - name (str): Basename of the file or directory against which the event was raised in case where the watched directory is the parent directory. None if the event was raised on the watched item itself. This field is always provided even if the string is ''. - pathname (str): Concatenation of 'path' and 'name'. - src_pathname (str): Only present for IN_MOVED_TO events and only in the case where IN_MOVED_FROM events are watched too. Holds the source pathname from where pathname was moved from. - cookie (int): Cookie. - dir (bool): True if the event was raised against a directory. c Cs’t ||¡t |j¡|_tr&|j|_z8|jrLtj   tj   |j |j¡¡|_ ntj   |j ¡|_ Wn.t yŒ}zt |¡WYd}~n d}~00dS)zH Concretely, this is the raw event plus inferred infos. N)rr rerzr1ÚCOMPATIBILITY_MODEÚ event_nameryr"rWÚabspathrXr0ÚAttributeErrorrOr )r Úrawrrrrr 7s ÿ zEvent.__init__Nr rrrrr¢sr¢c@seZdZdZdd„ZdS)ÚProcessEventErrorzD ProcessEventError Exception. Raised on ProcessEvent error. cCst ||¡dS)zT @param err: Exception error description. @type err: string Nr rrrrr OszProcessEventError.__init__Nr rrrrr¨Ksr¨c@s eZdZdZdd„Zdd„ZdS)Ú _ProcessEventz* Abstract processing event class. cCs„|j|jt@}tj |¡}|dur0td|ƒ‚t|d|dƒ}|durP||ƒSt|d| d¡ddƒ}|durz||ƒS| |¡S)a To behave like a functor the object must be callable. This method is a dispatch method. Its lookup order is: 1. process_MASKNAME method 2. process_FAMILY_NAME method 3. otherwise calls process_default @param event: Event to be processed. @type event: Event object @return: By convention when used from the ProcessEvent class: - Returning False or None (default value) means keep on executing next chained functors (see chain.py example). - Returning True instead means do not execute next processing functions. @rtype: bool @raise ProcessEventError: Event object undispatchable, unknown event. NzUnknown mask 0x%08xZprocess_Z process_IN_rŠrf) r1rurerwÚgetr¨r‘ÚsplitÚprocess_default)r ÚeventZ stripped_maskrzÚmethrrrÚ__call__[s  z_ProcessEvent.__call__cCs d|jjS)Nz<%s>)r—rr rrrrb~sz_ProcessEvent.__repr__N)rrrrr¯rbrrrrr©Ws#r©c@sZeZdZdZdd„Zdd„Zdd„Zdd „Zd d „Zd d „Z dd„Z dd„Z ddd„Z dS)Ú_SysProcessEventa« There is three kind of processing according to each event: 1. special handling (deletion from internal container, bug, ...). 2. default treatment: which is applied to the majority of events. 3. IN_ISDIR is never sent alone, he is piggybacked with a standard event, he is not processed as the others events, instead, its value is captured and appropriately aggregated to dst event. cCs||_||_i|_i|_dS)z¡ @param wm: Watch Manager. @type wm: WatchManager instance @param notifier: Notifier. @type notifier: Notifier instance N)Ú_watch_managerÚ _notifierÚ _mv_cookieÚ_mv)r ÚwmÚnotifierrrrr Œsz_SysProcessEvent.__init__cCsdt ¡}|j|jfD]J}t| ¡ƒD]8}|||dtddkr$t d||d¡||=q$qdS)zh Cleanup (delete) old (>1mn) records contained in self._mv_cookie and self._mv. rf)ZminuteszCleanup: deleting entry %srN) rÚnowr³r´ÚlistÚkeysrrOr )r Z date_cur_ÚseqÚkrrrÚcleanup™s z_SysProcessEvent.cleanupc CsP|jt@rF|j |j¡}tj |j|j¡}|j rF|  |¡sF|jj }|||j|j d|j |j d}|  |¡}|durF|dkrFtj |¡rFzxt |¡D]h}tj ||¡}|j |¡durÀqœtj |¡rÒt} ntj |¡rœttB} nqœt|| d|ƒ} |j | ¡qœWn<tyD} z"d} t | t| ƒ¡WYd} ~ n d} ~ 00| |¡S)zì If the event affects a directory and the auto_add flag of the targetted watch is set to True, a new watch is added on this new directory, with the same attribute values than those of this watch. F©Úproc_funÚrecÚauto_addÚexclude_filterNrz(process_IN_CREATE, invalid directory: %s)r1rur±Ú get_watchr5r"rWrXryrÀrÁÚ add_watchr¾rªÚisdirÚlistdirÚget_wdÚisfileror›r²Ú append_eventrFrOr r,r¬) r Ú raw_eventÚwatch_Z created_dirZaddwZaddw_retZcreated_dir_wdryÚinnerÚflagsÚraweventrÚmsgrrrÚprocess_IN_CREATE¥s< ý  ÿ   (z"_SysProcessEvent.process_IN_CREATEcCsR|j |j¡}|j}tj tj ||j¡¡}|t  ¡f|j |j <|  |d|j i¡S)zL Map the cookie with the source path (+ date for cleaning). r) r±rÂr5rWr"ÚnormpathrXryrr·r³rr¬)r rÉrÊÚpath_Úsrc_pathrrrÚprocess_IN_MOVED_FROMÕs z&_SysProcessEvent.process_IN_MOVED_FROMcCs´|j |j¡}|j}tj tj ||j¡¡}|j  |j ¡}d|j i}|durp|t   ¡f|j |d<|d|d<n8|jt@r¨|jr¨| |¡s¨|jj||j|jdd|jd| ||¡S)z^ Map the source path with the destination path (+ date for cleaning). rNrZ src_pathnameTr½)r±rÂr5rWr"rÐrXryr³rªrrr·r´r1rurÀrÁrÃr¾r¬)r rÉrÊrÑZdst_pathÚmv_Ú to_appendrrrÚprocess_IN_MOVED_TOßs" ÿ ýz$_SysProcessEvent.process_IN_MOVED_TOc CsÎ|j |j¡}|j}|j |¡}|r€|d}||_|tjj7}t|ƒ}|jj   ¡D]*}|j  |¡rRtj  ||j|d…¡|_qRnDt  d|j|tj tj  |jtjj¡¡¡|j d¡sÄ|jd7_| |¡S)a STATUS: the following bug has been fixed in recent kernels (FIXME: which version ?). Now it raises IN_DELETE_SELF instead. Old kernels were bugged, this event raised when the watched item were moved, so we had to update its path, but under some circumstances it was impossible: if its parent directory and its destination directory wasn't watched. The kernel (see include/linux/fsnotify.h) doesn't bring us enough informations like the destination path of moved items. rNzëThe pathname '%s' of this watch %s has probably changed and couldn't be updated, so it cannot be trusted anymore. To fix this error move directories/files only between watched parents directories, in this case e.g. put a watch on '%s'.z -unknown-path)r±rÂr5rWr´rªr"ÚsepÚlenÚwatchesÚvaluesrDrXrOÚerrorrÐÚpardirÚendswithr¬)r rÉrÊrÒrÔZ dest_pathZ src_path_lenr]rrrÚprocess_IN_MOVE_SELFýs(    ÿú z%_SysProcessEvent.process_IN_MOVE_SELFcCstd|jiƒS)z{ Only signal an overflow, most of the common flags are irrelevant for this event (path, wd, name). r1)r¢r1)r rÉrrrÚprocess_IN_Q_OVERFLOW'sz&_SysProcessEvent.process_IN_Q_OVERFLOWcCs| |¡}|j |j¡|S)a& The watch descriptor raised by this event is now ignored (forever), it can be safely deleted from the watch manager dictionary. After this event we can be sure that neither the event queue nor the system will raise an event associated to this wd again. )r¬r±Ú del_watchr5)r rÉZevent_rrrÚprocess_IN_IGNORED.s z#_SysProcessEvent.process_IN_IGNOREDNcCsp|j |j¡}|jttB@r$|j}nt|jt@ƒ}|j|j|j |j |dœ}t rV||d<|durh|  |¡t |ƒS)zÁ Commons handling for the followings events: IN_ACCESS, IN_MODIFY, IN_ATTRIB, IN_CLOSE_WRITE, IN_CLOSE_NOWRITE, IN_OPEN, IN_DELETE, IN_DELETE_SELF, IN_UNMOUNT. )r5r1rWryÚdirÚis_dirN)r±rÂr5r1rqrrrâÚboolrurWryr£Úupdater¢)r rÉrÕrÊZdir_r„rrrr¬9sü z _SysProcessEvent.process_default)N) rrrrr r¼rÏrÓrÖrÞrßrár¬rrrrr°‚s   0 * r°c@sFeZdZdZdZddd„Zdd„Zdd„Zd d „Zd d „Z d d„Z dS)Ú ProcessEventaQ Process events objects, can be specialized via subclassing, thus its behavior can be overriden: Note: you should not override __init__ in your subclass instead define a my_init() method, this method will be called automatically from the constructor of this class with its optionals parameters. 1. Provide specialized individual methods, e.g. process_IN_DELETE for processing a precise type of event (e.g. IN_DELETE in this case). 2. Or/and provide methods for processing events by 'family', e.g. process_IN_CLOSE method will process both IN_CLOSE_WRITE and IN_CLOSE_NOWRITE events (if process_IN_CLOSE_WRITE and process_IN_CLOSE_NOWRITE aren't defined though). 3. Or/and override process_default for catching and processing all the remaining types of events. NcKs||_|jfi|¤ŽdS)a­ Enable chaining of ProcessEvent instances. @param pevent: Optional callable object, will be called on event processing (before self). @type pevent: callable @param kargs: This constructor is implemented as a template method delegating its optionals keyworded arguments to the method my_init(). @type kargs: dict N)ÚpeventÚmy_init)r rçÚkargsrrrr fs zProcessEvent.__init__cKsdS)a= This method is called from ProcessEvent.__init__(). This method is empty here and must be redefined to be useful. In effect, if you need to specifically initialize your subclass' instance then you just have to override this method in your subclass. Then all the keyworded arguments passed to ProcessEvent.__init__() will be transmitted as parameters to this method. Beware you MUST pass keyword arguments though. @param kargs: optional delegated arguments from __init__(). @type kargs: dict Nr)r rérrrrèus zProcessEvent.my_initcCs,d}|jdur| |¡}|s(t ||¡SdS©NF)rçr©r¯)r r­Z stop_chainingrrrr¯„s   zProcessEvent.__call__cCs|jSr()rçr rrrÚ nested_peventszProcessEvent.nested_peventcCst d¡dS)a– By default this method only reports warning messages, you can overredide it by subclassing ProcessEvent and implement your own process_IN_Q_OVERFLOW method. The actions you can take on receiving this event is either to update the variable max_queued_events in order to handle more simultaneous events or to modify your code in order to accomplish a better filtering diminishing the number of raised events. Because this method is defined, IN_Q_OVERFLOW will never get transmitted as arguments to process_default calls. @param event: IN_Q_OVERFLOW event. @type event: dict zEvent queue overflowed.N)rOÚwarning©r r­rrrrß“sz"ProcessEvent.process_IN_Q_OVERFLOWcCsdS)ae Default processing event method. By default does nothing. Subclass ProcessEvent and redefine this method in order to modify its behavior. @param event: Event to be processed. Can be of any type of events but IN_Q_OVERFLOW events (see method process_IN_Q_OVERFLOW). @type event: Event instance Nrrírrrr¬£s zProcessEvent.process_default)N) rrrrrçr rèr¯rërßr¬rrrrræRs  ræc@s"eZdZdZddd„Zdd„ZdS)ÚPrintAllEventsz¡ Dummy class used to print events strings representations. For instance this class is used from command line to print all received events to stdout. NcCs|durtj}||_dS)z~ @param out: Where events will be written. @type out: Object providing a valid file object interface. N)rBÚstdoutÚ_out)r Úoutrrrrè´szPrintAllEvents.my_initcCs*|j t|ƒ¡|j d¡|j ¡dS)a$ Writes event string representation to file object provided to my_init(). @param event: Event to be processed. Can be of any type of events but IN_Q_OVERFLOW events (see method process_IN_Q_OVERFLOW). @type event: Event instance r^N)rðr_r,Úflushrírrrr¬½s  zPrintAllEvents.process_default)N©rrrrrèr¬rrrrrî¯s rîc@s eZdZdZdd„Zdd„ZdS)Ú ChainIfTruezc Makes conditional chaining depending on the result of the nested processing instance. cCs ||_dS©zJ Method automatically called from base class constructor. N©Z_func)r ÚfuncrrrrèÐszChainIfTrue.my_initcCs | |¡ Sr(rörírrrr¬ÖszChainIfTrue.process_defaultNrórrrrrôËsrôc@sBeZdZdZdd„Zdd„Zdd„Zdd „Zd d „Zdd d„Z dS)ÚStatszH Compute and display trivial statistics about processed events. cCst ¡|_i|_t ¡|_dSrõ)ÚtimeÚ _start_timeÚ_statsÚ threadingÚLockÚ _stats_lockr rrrrèÞs z Stats.my_initcCs\|j ¡z@|j d¡}|D] }|j |d¡}|d|j|<qW|j ¡n |j ¡0dS)z$ Processes |event|. ú|rrfN)rþÚacquirerzr«rûrªÚrelease)r r­Zeventsr¤Úcountrrrr¬æs  zStats.process_defaultcCs2|j ¡z|j ¡W|j ¡S|j ¡0dSr()rþrrûÚcopyrr rrrÚ _stats_copyós    þzStats._stats_copycCs| ¡}tt ¡|jƒ}d}|dkr4t|ƒd}n€d|krHdkrbnnd|d|df}nRd|krvdkr”nnd|d|ddf}n |dkr´d|d|ddf}||d <g}t| ¡d d „d D]&\}}| d t  |¡t  |¡f¡qÔdt  |j j ¡d |¡f}|S)Nr…é<Zseciz %dmn%dseci€Qz%dh%dmnz%dd%dhZ ElapsedTimecSs|dSr†rr‡rrrr~ rz Stats.__repr__..rˆz %s=%sz<%s%s >)rrYrùrúr,rŽr‚Úappendr’r“r•r–r—rrX)r ÚstatsÚelapsedZ elapsed_strÚlÚevrdr˜rrrrbús*ÿ ÿzStats.__repr__cCsNtjtjBtjBtjB}t ||d¡}t |t| ¡t   ¡ƒ¡t  |¡dS)zÕ Dumps statistics. @param filename: filename where stats will be dumped, filename is created and must not exist prior to this call. @type filename: string é€N) r"ÚO_WRONLYÚO_CREATÚ O_NOFOLLOWÚO_EXCLrVr_ÚbytesršÚlocaleÚgetpreferredencodingÚclose)r ÚfilenamerÌr/rrrÚdumpsz Stats.dumpé-csp| ¡}|sdSt| ¡ƒ}||‰dtt d|¡ƒd‰‡‡fdd„}d t|t|  ¡dd „d ƒ¡}|S) Nr…z%%-26s%%-%ds%%sú@rfcs>ˆt |d¡t dt|dˆƒ¡t d|dd¡fS)Nrrrfz%dÚyellow)r’r“r•rYÚsimpler‡©ZfmtZunityrrr÷'sþzStats.__str__..funcr^cSs|dSr†rr‡rrrr~+rzStats.__str__..rˆ) rÚmaxrÚrØr’r•rXÚmaprŽr‚)r ZscalerÚmr÷r˜rrrršs ÿ z Stats.__str__N)r) rrrrrèr¬rrbrršrrrrrøÚs  røc@seZdZdZdd„ZdS)Ú NotifierErrorz8 Notifier Exception. Raised on Notifier error. cCst ||¡dS)zW @param err: Exception string's description. @type err: string Nr rrrrr 4szNotifierError.__init__Nr rrrrr/src@s€eZdZdZddd„Zdd„Zdd „Zdd d „Zdd d„Zdd„Z dd„Z de j e j e j fdd„Z dd„Zddd„Zdd„ZdS) ÚNotifierz. Read notifications, process events. NrcCs„||_|j ¡|_t ¡|_|j |jtj¡d|_t ƒ|_ t |j|ƒ|_ ||_ |dur`tƒ|_ ||_||_||_d|_tƒ|_dS)aC Initialization. read_freq, threshold and timeout parameters are used when looping. @param watch_manager: Watch Manager. @type watch_manager: WatchManager instance @param default_proc_fun: Default processing method. If None, a new instance of PrintAllEvents will be assigned. @type default_proc_fun: instance of ProcessEvent @param read_freq: if read_freq == 0, events are read asap, if read_freq is > 0, this thread sleeps max(0, read_freq - (timeout / 1000)) seconds. But if timeout is None it may be different because poll is blocking waiting for something to read. @type read_freq: int @param threshold: File descriptor will be read only if the accumulated size to read becomes >= threshold. If != 0, you likely want to use it in combination with an appropriate value for read_freq because without that you would keep looping without really reading anything and that until the amount of events to read is >= threshold. At least with read_freq set you might sleep. @type threshold: int @param timeout: see read_freq above. If provided, it must be set in milliseconds. See https://docs.python.org/3/library/select.html#select.poll.poll @type timeout: int )r;r;NF)r±Úget_fdÚ_fdÚselectÚpollÚ_pollobjÚregisterÚPOLLINÚ_piperÚ_eventqr°Ú _sys_proc_funÚ_default_proc_funrîÚ _read_freqÚ _thresholdÚ_timeoutÚ _coalesceÚsetÚ _eventset©r Ú watch_managerÚdefault_proc_funÚ read_freqÚ thresholdÚtimeoutrrrr As  zNotifier.__init__cCs|j |¡dS)z‚ Append a raw event to the event queue. @param event: An event. @type event: _RawEvent instance. N)r(rrírrrrÈyszNotifier.append_eventcCs|jSr()r*r rrrr¾‚szNotifier.proc_funTcCs||_|s|j ¡dS)a Coalescing events. Events are usually processed by batchs, their size depend on various factors. Thus, before processing them, events received from inotify are aggregated in a fifo queue. If this coalescing option is enabled events are filtered based on their unicity, only unique events are enqueued, doublons are discarded. An event is unique when the combination of its fields (wd, mask, cookie, name) is unique among events of a same batch. After a batch of events is processed any events is accepted again. By default this option is disabled, you have to explictly call this function to turn it on. @param coalesce: Optional new coalescing value. True by default. @type coalesce: Bool N)r.r0Úclear)r ZcoalescerrrÚcoalesce_events…szNotifier.coalesce_eventsc Csšz|dur|j}|j |¡}Wqjtjyd}z,|jdtjkrNWYd}~qn‚WYd}~qd}~00qjq|r„|jd|ddkrˆdS|ddtj @S)aw Check for new events available to read, blocks up to timeout milliseconds. @param timeout: If specified it overrides the corresponding instance attribute _timeout. timeout must be sepcified in milliseconds. @type timeout: int @return: New events to read. @rtype: bool NrFrf) r-r$r#r"rÛÚargsr$ZEINTRr'r&)r r6r=rrrrÚ check_events˜szNotifier.check_eventsc Csbt ddg¡}t |jtj|d¡dkr*dS|d}||jkrTt d|j||j¡dSzt   |j|¡}Wn,t y’}zt |ƒ‚WYd}~n d}~00t d|¡d}||kr^d}t  d ||||…¡\}}} } t  d | |||||| …¡\} |  ¡} t||| | ƒ} |jrDt| ƒ}||jvrP|j |¡|j | ¡n |j | ¡||| 7}q¤dS) zN Read events from device, build _RawEvents, and enqueue them. Úirrfr;NzF(fd: %d) %d bytes available to read but threshold is fixed to %d byteszEvent queue size: %drjZiIIIz%ds)ÚarrayÚfcntlZioctlr!ÚtermiosZFIONREADr,rOr r"ÚreadÚ ExceptionrÚstructÚunpackÚdecoder›r.r,r0Úaddr(r)r Zbuf_Z queue_sizerUrÎZrsumZs_sizer5r1rZ fname_lenZbnameÚunamerÍZ raweventstrrrrÚ read_events¸sB þ  ÿ  ÿ   zNotifier.read_eventscCs²|jr”|j ¡}|jjr,t dt|ƒ¡q|j |j¡}|durh|j t @sh|j t @st  dt|ƒ¡q|  |¡}|rˆ|jrˆ| |¡q| |¡q|j  ¡|jr®|j ¡dS)z× Routine for processing events from queue by calling their associated proccessing method (an instance of ProcessEvent). It also does internal processings, to keep the system updated. zEvent ignored: %sNz0Unable to retrieve Watch object associated to %s)r(Úpopleftr±Ú ignore_eventsrOr r™rÂr5r1rsrtrìr)r¾r*r¼r.r0r7)r rÉrÊZreventrrrÚprocess_eventsãs&  ÿ     zNotifier.process_eventsc sÞˆdur4d}tj tjd¡p d}tj ||d¡‰ˆdkrXtj ˆ¡rXdˆ}t|ƒ‚‡‡‡fdd „}|ƒˆdkrÚtjtj Btj Btj B} t  ˆ| d ¡} t  | ttt ¡ƒd t ¡ƒ¡t | ¡t ‡fd d „¡dS)a pid_file: file where the pid will be written. If pid_file=None the pid is written to /var/run/.pid, if pid_file=False no pid_file is written. stdin, stdout, stderr: files associated to common streams. Nz /var/run/rrKz.pidFz-Cannot daemonize: pid file %s already exists.cs¶t ¡}|dkrJt ¡t ¡}|dkr>t d¡t d¡qTt d¡n t d¡t ˆtj¡}t |d¡t ˆtj tj Bd¡}t |d¡t ˆtj tj Bd¡}t |d¡dS)Nrú/ér rfrg) r"ÚforkÚsetsidÚchdirÚumaskÚ_exitrVÚO_RDONLYÚdup2r r )ÚpidZfd_inpZfd_outZfd_err)ÚstderrÚstdinrïrrÚ fork_daemons      z)Notifier.__daemonize..fork_daemonr r^cs t ˆ¡Sr()r"Úunlinkr)Úpid_filerrr~6rz&Notifier.__daemonize..)r"rWÚbasenamerBÚargvrXÚlexistsrr r rrrVr_rr,ÚgetpidrrrÚatexitr%) r rXrUrïrTÚdirnamerYrrVrÌZfd_pidr)rXrTrUrïrZ __daemonizes"ÿ zNotifier.__daemonizecCsB|jdkr>t ¡}|j||}|dkr>t d|¡t |¡dS)NrzNow sleeping %d seconds)r+rùrOr Úsleep)r Úref_timeZcur_timeZ sleep_amountrrrÚ_sleep8s   zNotifier._sleepFcKsŠ|r|jfi|¤ŽzF| ¡|dur6||ƒdur6Wq~t ¡}| ¡rX| |¡| ¡Wqtyzt d¡Yq~Yq0q|  ¡dS)a< Events are read only one time every min(read_freq, timeout) seconds at best and only if the size to read is >= threshold. After this method returns it must not be called again for the same instance. @param callback: Functor called after each event processing iteration. Expects to receive the notifier object (self) as first parameter. If this function returns True the loop is immediately terminated otherwise the loop method keeps looping. @type callback: callable object or function @param daemonize: This thread is daemonized if set to True. @type daemonize: boolean @param args: Optional and relevant only if daemonize is True. Remaining keyworded arguments are directly passed to daemonize see __daemonize() method. If pid_file=None or is set to a pathname the caller must ensure the file does not exist before this method is called otherwise an exception pyinotify.NotifierError will be raised. If pid_file=False it is still daemonized but the pid is not written in any file. @type args: various NTzPyinotify stops monitoring.) Ú_Notifier__daemonizerIrùr:rarFÚKeyboardInterruptrOr Ústop)r ÚcallbackZ daemonizer9r`rrrÚloopAs     z Notifier.loopcCs4|jdur*|j |j¡t |j¡d|_d|_dS)zÿ Close inotify's instance (close its file descriptor). It destroys all existing watches, pending events,... This method is automatically called at the end of loop(). Afterward it is invalid to access this instance. N)r!r$Ú unregisterr"rr)r rrrrdos   z Notifier.stop)NrrN)T)N)NF)rrrrr rÈr¾r8r:rFrIr"Údevnullrbrarfrdrrrrr<s ÿ 8   + ÿ 8 .rc@s2eZdZdZd dd„Zdd„Zdd „Zd d „ZdS) ÚThreadedNotifierav This notifier inherits from threading.Thread for instanciating a separate thread, and also inherits from Notifier, because it is a threaded notifier. Note that every functionality provided by this class is also provided through Notifier class. Moreover Notifier should be considered first because it is not threaded and could be easily daemonized. NrcCsNtj |¡t ¡|_t ||||||¡t ¡|_|j   |jdt j ¡dS)ax Initialization, initialize base classes. read_freq, threshold and timeout parameters are used when looping. @param watch_manager: Watch Manager. @type watch_manager: WatchManager instance @param default_proc_fun: Default processing method. See base class. @type default_proc_fun: instance of ProcessEvent @param read_freq: if read_freq == 0, events are read asap, if read_freq is > 0, this thread sleeps max(0, read_freq - (timeout / 1000)) seconds. @type read_freq: int @param threshold: File descriptor will be read only if the accumulated size to read becomes >= threshold. If != 0, you likely want to use it in combination with an appropriate value set for read_freq because without that you would keep looping without really reading anything and that until the amount of events to read is >= threshold. At least with read_freq you might sleep. @type threshold: int @param timeout: see read_freq above. If provided, it must be set in milliseconds. See https://docs.python.org/3/library/select.html#select.poll.poll @type timeout: int rN) rüÚThreadr r¢Ú _stop_eventrr"Úpiper'r$r%r"r&r1rrrr †s   ÿ zThreadedNotifier.__init__cCsh|j ¡t |jdd¡tj |¡t  |¡|j   |jd¡t  |jd¡t  |jd¡dS)zK Stop notifier's loop. Stop notification. Join the thread. rfsstoprN) rkr/r"r_r'rürjrXrrdr$rgrr rrrrd¬s   zThreadedNotifier.stopcCs:|j ¡s6| ¡t ¡}| ¡r| |¡| ¡qdS)a Thread's main loop. Don't meant to be called by user directly. Call inherited start() method instead. Events are read only once time every min(read_freq, timeout) seconds at best and only if the size of events to read is >= threshold. N)rkÚisSetrIrùr:rarF)r r`rrrrf¸s  zThreadedNotifier.loopcCs | ¡dS)a  Start thread's loop: read and process events until the method stop() is called. Never call this method directly, instead call the start() method inherited from threading.Thread, which then will call run() in its turn. N)rfr rrrÚrunËszThreadedNotifier.run)NrrN)rrrrr rdrfrnrrrrri}sÿ & ric@s"eZdZdZddd„Zdd„ZdS) Ú AsyncNotifierz‹ This notifier inherits from asyncore.file_dispatcher in order to be able to use pyinotify along with the asyncore framework. NrcCs*t ||||||¡tj ||j|¡dS)zÚ Initializes the async notifier. The only additional parameter is 'channel_map' which is the optional asyncore private map. See Notifier class for the meaning of the others parameters. N)rr ÚasyncoreÚfile_dispatcherr!)r r2r3r4r5r6Ú channel_maprrrr Üs ÿzAsyncNotifier.__init__cCs| ¡| ¡dS)z· When asyncore tells us we can read from the fd, we proceed processing events. This method can be overridden for handling a notification differently. N)rFrIr rrrÚ handle_readèszAsyncNotifier.handle_read)NrrNN)rrrrr rsrrrrroÖs ÿ roc@s*eZdZdZd dd„Zdd„Zdd „ZdS) ÚTornadoAsyncNotifierz" Tornado ioloop adapter. Nrc Cs8||_||_t ||||||¡| |j|j|j¡dS)a? Note that if later you must call ioloop.close() be sure to let the default parameter to all_fds=False. See example tornado_notifier.py for an example using this notifier. @param ioloop: Tornado's IO loop. @type ioloop: tornado.ioloop.IOLoop instance. @param callback: Functor called at the end of each call to handle_read (IOLoop's read handler). Expects to receive the notifier object (self) as single parameter. @type callback: callable object or function N)Úio_loopÚhandle_read_callbackrr Z add_handlerr!rsZREAD) r r2Ziolooprer3r4r5r6rrrrrr øs  ÿzTornadoAsyncNotifier.__init__cCs|j |j¡t |¡dSr()ruZremove_handlerr!rrdr rrrrdszTornadoAsyncNotifier.stopcOs(| ¡| ¡|jdur$| |¡dS)z0 See comment in AsyncNotifier. N©rFrIrv©r r9Úkwargsrrrrss z TornadoAsyncNotifier.handle_read)NNrrNN©rrrrr rdrsrrrrrtósþ rtc@s*eZdZdZd dd„Zdd„Zdd „ZdS) ÚAsyncioNotifierz0 asyncio/trollius event loop adapter. NrcCs4||_||_t ||||||¡| |j|j¡dS)aÐ See examples/asyncio_notifier.py for an example usage. @param loop: asyncio or trollius event loop instance. @type loop: asyncio.BaseEventLoop or trollius.BaseEventLoop instance. @param callback: Functor called at the end of each call to handle_read. Expects to receive the notifier object (self) as single parameter. @type callback: callable object or function N)rfrvrr Z add_readerr!rs)r r2rfrer3r4r5r6rrrr #s  ÿzAsyncioNotifier.__init__cCs|j |j¡t |¡dSr()rfZ remove_readerr!rrdr rrrrd7szAsyncioNotifier.stopcOs(| ¡| ¡|jdur$| |¡dSr(rwrxrrrrs;s zAsyncioNotifier.handle_read)NNrrNrzrrrrr{s ÿ r{c@s$eZdZdZdZdd„Zdd„ZdS)ÚWatchzE Represent a watch, i.e. a file or directory being watched. )r5rWr1r¾rÀrÁrâcCs8||_||_||_||_||_||_tj |j¡|_dS)a• Initializations. @param wd: Watch descriptor. @type wd: int @param path: Path of the file or directory being watched. @type path: str @param mask: Mask. @type mask: int @param proc_fun: Processing callable object. @type proc_fun: @param auto_add: Automatically add watches on new directories. @type auto_add: bool @param exclude_filter: Boolean function, used to exclude new directories from being automatically watched. See WatchManager.__init__ @type exclude_filter: callable object N) r5rWr1r¾rÀrÁr"rÄrâ)r r5rWr1r¾rÀrÁrrrr JszWatch.__init__csDd ‡fdd„ˆjDƒ¡}dt d¡t ˆjj¡|t d¡f}|S)zE @return: String representation. @rtype: str ú c s<g|]4}| d¡sdt |¡t d¡t tˆ|ƒ¡f‘qS)rŠz%s%s%sr‹)rDr’r“r”r•r‘)Ú.0rTr rrÚ js ü ÿþz"Watch.__repr__..z %s%s %s %srŒr)rXÚ __slots__r’r”r–r—r©r r˜rr rrbesü  ýzWatch.__repr__N)rrrrr€r rbrrrrr|Bsr|c@s0eZdZdZdd„Zdd„Zdd„Zdd „Zd S) Ú ExcludeFilterz/ ExcludeFilter is an exclusion filter. cCsTt|tƒr| |¡}nt|tƒr&|}nt‚g|_|D]}|j t |tj ¡¡q4dS)aZ Examples: ef1 = ExcludeFilter(["/etc/rc.*", "/etc/hostname"]) ef2 = ExcludeFilter("/my/path/exclude.lst") Where exclude.lst contains: /etc/rc.* /etc/hostname Note: it is not possible to exclude a file if its encapsulating directory is itself watched. See this issue for more details https://github.com/seb-m/pyinotify/issues/31 @param arg_lst: is either a list of patterns or a filename from which patterns will be loaded. @type arg_lst: list of str or str N) r+r,Ú_load_patterns_from_filer¸Ú TypeErrorÚ_lregexrÚreÚcompileÚUNICODE)r Zarg_lstÚlstÚregexrrrr {s   zExcludeFilter.__init__cCsbg}t|dƒ@}| ¡D]&}| ¡}|r| d¡r4q| |¡qWdƒn1sT0Y|S)NrUú#)rVÚ readlinesÚstriprDr)r rr‰r[ÚlineÚpatternrrrrƒ—s  *z&ExcludeFilter._load_patterns_from_filecCs| |¡duSr()Úmatch)r rŠrWrrrÚ_match¢szExcludeFilter._matchcCs"|jD]}| ||¡rdSqdS)zã @param path: Path to match against provided regexps. @type path: str @return: Return True if path has been matched and should be excluded, False otherwise. @rtype: bool TF)r…r‘)r rWrŠrrrr¯¥s  zExcludeFilter.__call__N)rrrrr rƒr‘r¯rrrrr‚ws  r‚c@seZdZdZdd„ZdS)ÚWatchManagerErrorzX WatchManager Exception. Raised on error encountered on watches operations. cCs||_t ||¡dS)a @param msg: Exception string's description. @type msg: string @param wmd: This dictionary contains the wd assigned to paths of the same call for which watches were successfully added. @type wmd: dict N)Úwmdr@r )r rÎr“rrrr ¸szWatchManagerError.__init__Nr rrrrr’³sr’c@sÎeZdZdZdd„fdd„Zdd„Zdd „Zd d „Zd d „Ze dd„ƒZ dd„Z dd„Z dd„Z d0dd„Zdd„Zd1dd„Zdd „Zd!d"„Zd#d$„Zd%d&„Zd2d'd(„Zd)d*„Zd+d,„Zd-d.„Ze eed/ƒZdS)3Ú WatchManagera Provide operations for watching files and directories. Its internal dictionary is used to reference watched items. When used inside threaded code, one must instanciate as many WatchManager instances as there are ThreadedNotifier instances. cCsdSrêr©rWrrrr~ÌrzWatchManager.cCs\d|_||_i|_t ¡|_|jdur,tƒ‚|j ¡|_|jdkrXd}t ||j  ¡ƒ‚dS)aR Initialization: init inotify, init watch manager dictionary. Raise OSError if initialization fails, raise InotifyBindingNotFoundError if no inotify binding was found (through ctypes or from direct access to syscalls). @param exclude_filter: boolean function, returns True if current path must be excluded from being watched. Convenient for providing a common exclusion filter for every call to add_watch. @type exclude_filter: callable object FNrz-Cannot initialize new instance of inotify, %s) Ú_ignore_eventsÚ_exclude_filterÚ_wmdrrÚ_inotify_wrapperrr*r!rFr')r rÁrrrrr Ìs     zWatchManager.__init__cCst |j¡dS)a Close inotify's file descriptor, this action will also automatically remove (i.e. stop watching) all its associated watch descriptors. After a call to this method the WatchManager's instance become useless and cannot be reused, a new instance must then be instanciated. It makes sense to call this method in few situations for instance if several independant WatchManager must be instanciated or if all watches must be removed and no other watches need to be added. N)r"rr!r rrrræs zWatchManager.closecCs|jS)zs Return assigned inotify's file descriptor. @return: File descriptor. @rtype: int )r!r rrrr òszWatchManager.get_fdcCs |j |¡S)zz Get watch from provided watch descriptor wd. @param wd: Watch descriptor. @type wd: int )r˜rª)r r5rrrrÂûszWatchManager.get_watchc CsHz |j|=Wn6tyB}zt dt|ƒ¡WYd}~n d}~00dS)zƒ Remove watch entry associated to watch descriptor wd. @param wd: Watch descriptor. @type wd: int z)Cannot delete unknown watch descriptor %sN)r˜ÚKeyErrorrOrÛr,)r r5rrrrràs zWatchManager.del_watchcCs|jS)z• Get a reference on the internal watch manager dictionary. @return: Internal watch manager dictionary. @rtype: dict )r˜r rrrrÙszWatchManager.watchescCs tj |¡S)zW Format path to its internal (stored in watch manager) representation. )r"rWrÐ)r rWrrrZ __format_pathszWatchManager.__format_pathcCsj| |¡}|r|t@s|tO}|j |j||¡}|dkr<|St||||||d}||j|<t d|¡|S)z‡ Add a watch on path, build a Watch object and insert it in the watch manager dictionary. Return the wd value. r)r5rWr1r¾rÀrÁzNew %s) Ú_WatchManager__format_pathror™r2r!r|r˜rOr )r rWr1r¾rÀrÁr5ZwatchrrrZ __add_watch!s   ÿ  zWatchManager.__add_watchcCs|rt |¡S|gSdSr()ÚglobZiglob)r rWÚdo_globrrrZ__glob3s zWatchManager.__globNFTc  CsÀi} |dur|j}| |¡D]ž} t| tƒs4d| |<q| | |¡D]x} | | |¡D]f} || ƒs®| | ||||¡} | | <| dkr¶d| | |j ¡f}|r¢t   |¡q¶t || ƒ‚qPd| | <qPq@q| S)an Add watch(s) on the provided |path|(s) with associated |mask| flag value and optionally with a processing |proc_fun| function and recursive flag |rec| set to True. All |path| components _must_ be str (i.e. unicode) objects. If |path| is already watched it is ignored, but if it is called with option rec=True a watch is put on each one of its not-watched subdirectory. @param path: Path to watch, the path can either be a file or a directory. Also accepts a sequence (list) of paths. @type path: string or list of strings @param mask: Bitmask of events. @type mask: int @param proc_fun: Processing object. @type proc_fun: function or ProcessEvent instance or instance of one of its subclasses or callable object. @param rec: Recursively add watches from path on all its subdirectories, set to False by default (doesn't follows symlinks in any case). @type rec: bool @param auto_add: Automatically add watches on newly created directories in watched parent |path| directory. If |auto_add| is True, IN_CREATE is ored with |mask| when the watch is added. @type auto_add: bool @param do_glob: Do globbing on pathname (see standard globbing module for more informations). @type do_glob: bool @param quiet: if False raises a WatchManagerError exception on error. See example not_quiet.py. @type quiet: bool @param exclude_filter: predicate (boolean function), which returns True if the current path must be excluded from being watched. This argument has precedence over exclude_filter passed to the class' constructor. @type exclude_filter: callable object @return: dict of paths associated to watch descriptors. A wd value is positive if the watch was added sucessfully, otherwise the value is negative. If the path was invalid or was already watched it is not included into this returned dictionary. @rtype: dict of {str: int} Néýÿÿÿrz$add_watch: cannot watch %s WD=%d, %séþÿÿÿ) r—Ú_WatchManager__format_paramr+r,Ú_WatchManager__globÚ_WatchManager__walk_recÚ_WatchManager__add_watchr™r'rOrÛr’)r rWr1r¾r¿rÀrÚquietrÁÚret_ZnpathÚapathZrpathr5rrrrrÃ9s4/ ý ÿÿ  zWatchManager.add_watchccs²|D]¨}| |¡}|dur|Vnqtj |¡s2qtj |¡}t|ƒ}|j ¡D]Z}|dj}tj ||g¡}|tj ksžt|ƒ|krPt|ƒ|krP||tj krP|dj VqPqdS)a( Get every wd from self._wmd if its path is under the path of one (at least) of those in lpath. Doesn't follow symlinks. @param lpath: list of watch descriptor @type lpath: list of int @return: list of watch descriptor @rtype: list of int Nrf) Úget_pathr"rWrÄrÐrØr˜r‚Ú commonprefixr×r5)r Zlpathr¡ÚrootZlendÚiwdZcurZprefrrrZ __get_sub_rec‹s$      ÿ þzWatchManager.__get_sub_reccCs| |¡}|r| |¡}i}|D]Ü} | | ¡} | r:| dkr\d| } |rRt | ¡q t| |ƒ‚|r¼|j |j| |¡} | dkr°d|| <d| | |j  ¡f} |r¦t | ¡q t| |ƒ‚| | ks¼J‚|sÄ|rÎ|j | } |rØ|| _ |râ|| _ d|| <t  d|j | ¡q |S)a¶ Update existing watch descriptors |wd|. The |mask| value, the processing object |proc_fun|, the recursive param |rec| and the |auto_add| and |quiet| flags can all be updated. @param wd: Watch Descriptor to update. Also accepts a list of watch descriptors. @type wd: int or list of int @param mask: Optional new bitmask of events. @type mask: int @param proc_fun: Optional new processing function. @type proc_fun: function or ProcessEvent instance or instance of one of its subclasses or callable object. @param rec: Optionally adds watches recursively on all subdirectories contained into |wd| directory. @type rec: bool @param auto_add: Automatically adds watches on newly created directories in the watch's path corresponding to |wd|. If |auto_add| is True, IN_CREATE is ored with |mask| when the watch is updated. @type auto_add: bool @param quiet: If False raises a WatchManagerError exception on error. See example not_quiet.py @type quiet: bool @return: dict of watch descriptors associated to booleans values. True if the corresponding wd has been successfully updated, False otherwise. @rtype: dict of {int: bool} rzupdate_watch: invalid WD=%dFz(update_watch: cannot update %s WD=%d, %sTzUpdated watch - %s)r Ú_WatchManager__get_sub_recr§rOrÛr’r™r2r!r'r˜r¾rÀr )r r5r1r¾r¿rÀr¤Úlwdr¥Úawdr¦rÚwd_rÊrrrÚ update_watch®sF       ÿÿ    zWatchManager.update_watchccs&t|tƒr|D] }|Vqn|VdS)zŽ @param param: Parameter. @type param: string or int @return: wrap param. @rtype: list of type(param) N)r+r¸)r ZparamZp_rrrZ__format_paramös  zWatchManager.__format_paramcCs8| |¡}|j ¡D]}|dj|kr|dSqdS)aF Returns the watch descriptor associated to path. This method presents a prohibitive cost, always prefer to keep the WD returned by add_watch(). If the path is unknown it returns None. @param path: Path. @type path: str @return: WD or None. @rtype: int or None rfrN)r›r˜r‚rW)r rWrªrrrrÆs zWatchManager.get_wdcCs|j |¡}|dur|jSdS)zÐ Returns the path associated to WD, if WD is unknown it returns None. @param wd: Watch descriptor. @type wd: int @return: Path or None. @rtype: string or None N)r˜rªrW)r r5rÊrrrr§s zWatchManager.get_pathccsD|rtj |¡stj |¡s$|Vnt |¡D]\}}}|Vq.dS)a3 Yields each subdirectories of top, doesn't follow symlinks. If rec is false, only yield top. @param top: root directory. @type top: string @param rec: recursive flag. @type rec: bool @return: path of one subdirectory. @rtype: string N)r"rWÚislinkrÄÚwalk)r Útopr¿r©ÚdirsÚfilesrrrZ __walk_rec s zWatchManager.__walk_recc Cs¤| |¡}|r| |¡}i}|D]~}|j |j|¡}|dkrpd||<d||j ¡f}|rft |¡q t||ƒ‚||j vr‚|j |=d||<t  d||  |¡¡q |S)aÈ Removes watch(s). @param wd: Watch Descriptor of the file or directory to unwatch. Also accepts a list of WDs. @type wd: int or list of int. @param rec: Recursively removes watches on every already watched subdirectories and subfiles. @type rec: bool @param quiet: If False raises a WatchManagerError exception on error. See example not_quiet.py @type quiet: bool @return: dict of watch descriptors associated to booleans values. True if the corresponding wd has been successfully removed, False otherwise. @rtype: dict of {int: bool} rFz!rm_watch: cannot remove WD=%d, %sTzWatch WD=%d (%s) removed) r r«r™r6r!r'rOrÛr’r˜r r§) r r5r¿r¤r¬r¥r­r®rrrrÚrm_watch2s(   ÿ   zWatchManager.rm_watchc sbtj |¡}|dkriStj |¡‰|ttBO}‡fdd„}|j|||t|dƒddddd„dS) ad Watch a transient file, which will be created and deleted frequently over time (e.g. pid file). @attention: Currently under the call to this function it is not possible to correctly watch the events triggered into the same base directory than the directory where is located this watched transient file. For instance it would be wrong to make these two successive calls: wm.watch_transient_file('/var/run/foo.pid', ...) and wm.add_watch('/var/run/', ...) @param filename: Filename. @type filename: string @param mask: Bitmask of events, should contain IN_CREATE and IN_DELETE. @type mask: int @param proc_class: ProcessEvent (or of one of its subclass), beware of accepting a ProcessEvent's instance as argument into __init__, see transient_file.py example for more details. @type proc_class: ProcessEvent's instance or of one of its subclasses. @return: Same as add_watch(). @rtype: Same as add_watch(). r…cst|dƒdurdSˆ|jkS)NryF)r‘ry)r­©rYrrÚcmp_name|sz3WatchManager.watch_transient_file..cmp_name)r÷FcSsdSrêrr•rrrr~„rz3WatchManager.watch_transient_file..)r¾r¿rÀrrÁ)r"rWr^rYrorprÃrô)r rr1Z proc_classr^r·rr¶rÚwatch_transient_file]s     üz!WatchManager.watch_transient_filecCs|jSr(©r–r rrrÚget_ignore_events†szWatchManager.get_ignore_eventscCs ||_dSr(r¹)r r`rrrÚset_ignore_events‰szWatchManager.set_ignore_eventsz'Make watch manager ignoring new events.)NFFFTN)NNFFT)FT)rrrrr rr rÂràrcrÙr›r£r¡rÃr«r¯r rÆr§r¢rµr¸rºr»rHrrrrr”Äs<     þ R#ÿ H   +)ÿr”c@sBeZdZdZddd„Zdd„Zdd„Zd d „Zd d „Zd d„Z dS)ÚRawOutputFormatz( Format string representations. NcCs|pi|_dSr()Úformat)r r½rrrr ”szRawOutputFormat.__init__cCs2t|tƒst|ƒ}|j |d¡||j dd¡S)Nr…Únormal)r+r,r½rª)r r˜Z attributerrrr—s   ÿzRawOutputFormat.simplecCs | |d¡S)zPunctuation color.r¾©rrrrrr”szRawOutputFormat.punctuationcCs | |d¡S)zField value color.Úpurpler¿rrrrr•¡szRawOutputFormat.field_valuecCs | |d¡S)zField name color.Úbluer¿rrrrr“¥szRawOutputFormat.field_namecCs|j dd¡| |d¡S)zClass name color.Úredr…Úbold)r½rªrrrrrr–©szRawOutputFormat.class_name)N) rrrrr rr”r•r“r–rrrrr¼s r¼c@seZdZdZdd„ZdS)ÚColoredOutputFormatz0 Format colored string representations. c Cs.ddddddddd d d d d œ }t ||¡dS)Nzzzzzzzzzzzz) r¾ZblackrÂZgreenrrÁrÀZcyanrÃZulineZblinkÚinvert)r¼r )r Úfrrrr ³sõ zColoredOutputFormat.__init__Nr rrrrrįsrÄcCs<ttdtƒtƒD] }| d¡rtt|tƒ|ƒqdadS)a· Use this function to turn on the compatibility mode. The compatibility mode is used to improve compatibility with Pyinotify 0.7.1 (or older) programs. The compatibility mode provides additional variables 'is_dir', 'event_name', 'EventsCodes.IN_*' and 'EventsCodes.ALL_EVENTS' as Pyinotify 0.7.1 provided. Do not call this function from new programs!! Especially if there are developped for Pyinotify >= 0.8.x. r€ZIN_TN)rƒrer€ÚglobalsrDr£)ZevnamerrrÚcompatibility_modeÃs   rÈc s ddlm}d}||d}|jddddd d |jd d dd dd |jdddddd |jdddddd |jdddddd|jddddd d |jd!d"dd#d$d |jd%d&dd'd(d |jd)d*d+d,d-d | ¡\‰}ˆjrêt d.¡ˆjrøtt ƒˆj st ƒa t |ƒd/krd0}n|}tƒ}ˆjr>t|tƒd1d2}nt|tƒd3}d}ˆjržˆj d4¡}|D]2} tj | d¡} | rŠ|| O}n| d5| ¡qhnt}d6} ˆjrºd7d8„} | } ˆjrÒ‡fd9d8„} | } t d:|¡|j||ˆjˆjˆjd;|j | d<d6S)=z‘ By default the watched path is '/tmp' and all types of events are monitored. Events monitoring serves forever, type c^c to stop it. r)Ú OptionParserz.usage: %prog [options] [path1] [path2] [pathn])Úusagez-vz --verboseÚ store_trueÚverbosez Verbose mode)ÚactionÚdestÚhelpz-rz --recursiveÚ recursivez Add watches recursively on pathsz-az --auto_addrÀz,Automatically add watches on new directoriesz-gz--globrœzTreat paths as globsz-ez --events-listz EVENT[,...]Ú events_listzpA comma-separated list of events to watch for - see the documentation for valid options (defaults to everything))ÚmetavarrÎrÏz-sz--statsrzDisplay dummy statisticsz-Vz --versionr zPyinotify versionz-fz --raw-formatÚ raw_formatzDisable enhanced output format.z-cz --commandÚstoreÚcommandzShell command to run upon eventé rfz/tmpé)r3r4)r3ú,z4The event '%s' specified with option -e is not validNcSsNtj t| ¡ƒ¡tj d¡tj t| ¡ƒ¡tj d¡tj ¡dS)Nr^)rBrïr_r™r¾r,rò©r˜rrrÚcb$ s   zcommand_line..cbcstjˆjdddS)NT)Úshell)Ú subprocessÚPopenrÕrÙ©ÚoptionsrrrÚ. sz2Start monitoring %s, (press c^c to halt pyinotify))r¿rÀr)re)!ZoptparserÉZ add_optionÚ parse_argsrÌrOrNr ÚprintÚ __version__rÓrÄr’rØr”rrrørîrÑr«reÚ ALL_FLAGSrªrÛr€rÕr rÃrÐrÀrœrf) rÉrÊÚparserr9rWrµr¶r1rÑr ZevcodeZcb_funrÚrrÞrÚ command_lineÔs   ÿ þ þ þ þ þ ÿ þ þ    ÿ  råÚ__main__)Wrr@rrrBÚ version_infor rür"r"rAr=r$r>r<rMr]Ú collectionsrrrrùr†rprœrrÜÚ functoolsrÚ ImportErrorrZ ctypes.utilrÚ __author__râr£rrrrrPrOrQÚattrnamerÇrerãrwr{r‚ZflagcZvalcrƒråryÚvalrvrÚr€rr›r¢r¨r©r°rærîrôrørrrjrirqrortr{r|r‚r’r”r¼r’rÄrÈrårrrrrÚsº         .%< 2s     +$. +Q]U CY*%5<Oe