a ]l=b[@sdZGdddeZGdddeZddlZejdkr@eejddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlmZdd lmZmZddlZddlZddlZddlZddlZddlZzdd lmZWneyYn0zddlZddlZWney,dZYn0z ddl Z WneyRdZ Yn0d Z!d Z"d a#GdddeZ$GdddZ%Gddde%Z&Gddde%Z'ddZ(e(Z)GdddZ*dD]Z+e*e+e,e+<qGdddZ-ie-_.ie-_/e-j01D]J\Z2Z3e4e-e2e3e-j.5e3e31D]\Z6Z7e7e,e6<e6e-j/e7<q qedde-j89Z: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/eAZBGd0d1d1eAZCGd2d3d3eAZDGd4d5d5eZEGd6d7d7ZFGd8d9d9ejGeFZHGd:d;d;ejIeFZJGdd?d?eFZLGd@dAdAZMGdBdCdCZNGdDdEdEeZOGdFdGdGZPGdHdIdIZQeQaRGdJdKdKeQZSdLdMZTdNdOZUeVdPkreUdS)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@seZdZdZddZdS)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.0Nr__init__)selfversionrrrr (s z&UnsupportedPythonVersionError.__init__Nrrrrr rrrrr$srN)r)deque)datetime timedelta)reducez#seb@dbzteam.org (Sebastien Martini)z0.9.6Fc@seZdZdZddZdS)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@sDeZdZdZeddZddZddZdd 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_CtypesLibcINotifyWrapperinitinotify_syscalls_INotifySyscallsWrapper)inotifyrrrcreatevszINotifyWrapper.createcCs|S)z< Return None is no errno code is available. ) _get_errnor rrr get_errnoszINotifyWrapper.get_errnocCs,|}|durdSdt|tj|fS)NzErrno: no errno supportz Errno=%s (%s))r!osstrerrorerrno errorcode)r coderrr str_errnoszINotifyWrapper.str_errnocCs|SN) _inotify_initr rrr inotify_initszINotifyWrapper.inotify_initcCst|tsJ||||Sr() isinstancestr_inotify_add_watchr fdpathnamemaskrrrinotify_add_watchsz INotifyWrapper.inotify_add_watchcCs |||Sr()_inotify_rm_watchr r/wdrrrinotify_rm_watchszINotifyWrapper.inotify_rm_watchN) rrrr staticmethodrr!r'r*r2r6rrrrrqs rc@s<eZdZddZddZddZddZd d Zd d Zd S)rcCs d|_dSr( _last_errnor rrrr sz _INotifySyscallsWrapper.__init__cCs tsJdS)NT)rr rrrrsz_INotifySyscallsWrapper.initcCs|jSr(r8r rrrrsz"_INotifySyscallsWrapper._get_errnoc Cs@z t}Wn.ty:}z|j|_WYd}~dSd}~00|SN)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/r5retrrrrr3s z)_INotifySyscallsWrapper._inotify_rm_watchN rrrr rrr)r-r3rrrrrs rc@s<eZdZddZddZddZddZd d Zd d Zd S)rcCsd|_d|_dSr()_libc_get_errno_funcr rrrr sz"_CtypesLibcINotifyWrapper.__init__c CstsJd}tjdrd}d}ztj|}WnttfyFYn0tj|dd|_ tj |_ t |j drt |j drt |j dsd Sg|j j _tj|j j _tjtjtjg|j j_tj|j j_tjtjg|j j_tj|j j_dS) NcZfreebsdrT)Z use_errnor*r2r6F)rsysplatform startswithutilZ find_libraryOSErrorr<ZCDLLr?r!r@hasattrr*argtypesZc_intZrestypeZc_char_pZc_uint32r2r6)r Z try_libc_nameZ libc_namerrrrs4         z_CtypesLibcINotifyWrapper.initcCs|js J|Sr()r@r rrrrs z$_CtypesLibcINotifyWrapper._get_errnocCs|jdusJ|jSr()r?r*r rrrr)sz'_CtypesLibcINotifyWrapper._inotify_initcCs6|jdusJ|t}t|}|j|||Sr()r?encoderBgetfilesystemencodingrZcreate_string_bufferr2r.rrrr-s z,_CtypesLibcINotifyWrapper._inotify_add_watchcCs|jdusJ|j||Sr()r?r6r4rrrr3sz+_CtypesLibcINotifyWrapper._inotify_rm_watchNr>rrrrrs  rcCs:td}t}|td|||d|S)zInitialize logger instance. pyinotifyz0[%(asctime)s %(name)s %(levelname)s] %(message)s)loggingZ getLoggerZ StreamHandlerZ setFormatterZ FormatterZ addHandlersetLevel)logZconsole_handlerrrr logger_inits   rPc@s:eZdZdZddZddZddZeeeZdd 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|jd}t|WdS1s:0YdS)z Gets attribute's value. @return: stored value. @rtype: int @raise IOError: if corresponding file in /proc/sys cannot be read. rN)openr"pathjoinrRrSintreadline)r file_objrrrget_valszProcINotify.get_valcCsNttj|j|jd"}|t|dWdn1s@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"rWrXrRrSwriter,)r nvalr[rrrset_val&szProcINotify.set_valcCsd|j|fS)Nz<%s=%d>)rSr\r rrr__repr__3szProcINotify.__repr__N) rrrrr r\rapropertyvaluerbrrrrrQs   rQ)Zmax_queued_eventsZmax_user_instancesZmax_user_watchesc @s\eZdZdZdddddddd d d d d d ddddddddddddZddZeeZdS) 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_DELETEIN_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_ADDIN_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)r1msnamerrrmasknames zEventsCodes.masknameN)rrrrFLAG_COLLECTIONSrzr7rrrrreDs8= recCs||BSr(r)xyrrrr~ ALL_EVENTSc@s(eZdZdZddZddZddZdS) _Eventzw Event structure, represent events raised by the system. This is the base class and should be subclassed. cCs"|D]}t|g|RqdS)z Attach attributes (contained in dict_) to self. @param dict_: Set of attributes. @type dict_: dictionary N)itemssetattr)r dict_Ztplrrrr s z_Event.__init__cCsd}t|jdddD]b\}}|dr.q|dkrFtt||}nt|trX|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|dSNrrr|rrrr~rz!_Event.__repr__..key_r1z''z %s%s%s=z %s%s%s %s<>)sorted__dict__rrDhexgetattrr+r, output_format field_name punctuation field_value class_name __class__r)r srTrdrrrrbs$     z_Event.__repr__cCst|Sr()reprr rrr__str__sz_Event.__str__N)rrrrr rbrrrrrrs rc@s eZdZdZddZddZdS) _RawEventzm Raw event, it contains only the informations provided by the system. It doesn't infer anything. cCs8d|_||||dd}t||tt|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)r5r1cookiery)_strrstriprr rOdebugr,)r r5r1rrydrrrr s z_RawEvent.__init__cCs|jdurt||_|jSr()rrrr rrrrs  z_RawEvent.__str__N)rrrrr rrrrrrsrc@seZdZdZddZdS)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 Cst||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 rerzr1COMPATIBILITY_MODE event_nameryr"rWabspathrXr0AttributeErrorrOr)r rawrrrrr 7s  zEvent.__init__Nr rrrrrsrc@seZdZdZddZdS)ProcessEventErrorzD ProcessEventError Exception. Raised on ProcessEvent error. cCst||dS)zT @param err: Exception error description. @type err: string Nr rrrrr OszProcessEventError.__init__Nr rrrrrKsrc@s eZdZdZddZddZdS) _ProcessEventz* Abstract processing event class. cCs|j|jt@}tj|}|dur0td|t|d|d}|durP||St|d|ddd}|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_rrf) r1rurerwgetrrsplitprocess_default)r eventZ stripped_maskrzmethrrr__call__[s  z_ProcessEvent.__call__cCs d|jjS)Nz<%s>)rrr rrrrb~sz_ProcessEvent.__repr__N)rrrrrrbrrrrrWs#rc@sZeZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ dddZ 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 wmnotifierrrrr sz_SysProcessEvent.__init__cCsdt}|j|jfD]J}t|D]8}|||dtddkr$td||d||=q$qdS)zh Cleanup (delete) old (>1mn) records contained in self._mv_cookie and self._mv. rf)ZminuteszCleanup: deleting entry %srN) rnowrrlistkeysrrOr)r Z date_cur_seqkrrrcleanups 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|durqtj|rt} ntj|rttB} nqt|| d|} |j| qWn<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. Fproc_funrecauto_addexclude_filterNrz(process_IN_CREATE, invalid directory: %s)r1rur get_watchr5r"rWrXryrr add_watchrrisdirlistdirget_wdisfilerorr append_eventrFrOrr,r) r raw_eventwatch_Z created_dirZaddwZaddw_retZcreated_dir_wdryinnerflagsraweventrmsgrrrprocess_IN_CREATEs<      (z"_SysProcessEvent.process_IN_CREATEcCsR|j|j}|j}tjtj||j}|t f|j |j <| |d|j iS)zL Map the cookie with the source path (+ date for cleaning). r) rrr5rWr"normpathrXryrrrrr)r rrpath_src_pathrrrprocess_IN_MOVED_FROMs z&_SysProcessEvent.process_IN_MOVED_FROMcCs|j|j}|j}tjtj||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)rrr5rWr"rrXryrrrrrrr1rurrrrr)r rrrZdst_pathmv_ to_appendrrrprocess_IN_MOVED_TOs"  z$_SysProcessEvent.process_IN_MOVED_TOc Cs|j|j}|j}|j|}|r|d}||_|tjj7}t|}|jj D]*}|j |rRtj ||j|d|_qRnDt d|j|tjtj |jtjj|jds|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. rNzThe 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)rrr5rWrrr"seplenwatchesvaluesrDrXrOerrorrpardirendswithr)r rrrrZ dest_pathZ src_path_lenr]rrrprocess_IN_MOVE_SELFs(     z%_SysProcessEvent.process_IN_MOVE_SELFcCstd|jiS)z{ Only signal an overflow, most of the common flags are irrelevant for this event (path, wd, name). r1)rr1)r rrrrprocess_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. )rr del_watchr5)r rZevent_rrrprocess_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. )r5r1rWrydiris_dirN)rrr5r1rqrrrboolrurWryrupdater)r rrrZdir_rrrrr9s z _SysProcessEvent.process_default)N) rrrrr rrrrrrrrrrrrrs   0 * rc@sFeZdZdZdZdddZddZddZd d Zd d Z d dZ 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)peventmy_init)r rkargsrrrr 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 rrrrrus zProcessEvent.my_initcCs,d}|jdur||}|s(t||SdSNF)rrr)r rZ stop_chainingrrrrs   zProcessEvent.__call__cCs|jSr()rr rrr nested_peventszProcessEvent.nested_peventcCstddS)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)rOwarningr rrrrrsz"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 Nrrrrrrs zProcessEvent.process_default)N) rrrrrr rrrrrrrrrrRs  rc@s"eZdZdZdddZddZdS)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)rBstdout_out)r outrrrrszPrintAllEvents.my_initcCs*|jt||jd|jdS)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)rr_r,flushrrrrrs  zPrintAllEvents.process_default)Nrrrrrrrrrrrs rc@s eZdZdZddZddZdS) ChainIfTruezc Makes conditional chaining depending on the result of the nested processing instance. cCs ||_dSzJ Method automatically called from base class constructor. NZ_func)r funcrrrrszChainIfTrue.my_initcCs || Sr(rrrrrrszChainIfTrue.process_defaultNrrrrrrsrc@sBeZdZdZddZddZddZdd Zd d Zdd dZ dS)StatszH Compute and display trivial statistics about processed events. cCst|_i|_t|_dSr)time _start_time_stats threadingLock _stats_lockr rrrrs z Stats.my_initcCs\|jz@|jd}|D] }|j|d}|d|j|<qW|jn |j0dS)z$ Processes |event|. |rrfN)racquirerzrrrrelease)r rZeventsrcountrrrrs  zStats.process_defaultcCs2|jz|jW|jS|j0dSr()rrrcopyrr rrr _stats_copys    zStats._stats_copycCs|}tt|j}d}|dkr4t|d}nd|krHdkrbnnd|d|df}nRd|krvdkrnnd|d|ddf}n |dkrd|d|ddf}||d <g}t|d d d D]&\}}|d t |t |fqdt |j j d|f}|S)Nr<Zseciz %dmn%dseciQz%dh%dmnz%dd%dhZ ElapsedTimecSs|dSrrrrrrr~ rz Stats.__repr__..rz %s=%sz<%s%s >)rrYrrr,rrappendrrrrrrrX)r statselapsedZ elapsed_strlevrdrrrrrbs* 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_WRONLYO_CREAT O_NOFOLLOWO_EXCLrVr_bytesrlocalegetpreferredencodingclose)r filenamerr/rrrdumpsz Stats.dump-csp|}|sdSt|}||dttd|dfdd}dt|t| dd d }|S) Nrz%%-26s%%-%ds%%s@rfcs>t|dtdt|dtd|ddfS)Nrrrfz%dyellow)rrrrYsimplerZfmtZunityrrr'szStats.__str__..funcr^cSs|dSrrrrrrr~+rzStats.__str__..r) rmaxrrrrrXmaprr)r Zscalermrrrrrrs  z Stats.__str__N)r) rrrrrrrrbrrrrrrrs  rc@seZdZdZddZdS) 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@seZdZdZdddZddZdd Zdd d Zdd dZddZ ddZ de j e j e j fddZ ddZdddZddZdS) Notifierz. Read notifications, process events. NrcCs||_|j|_t|_|j|jtjd|_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)rget_fd_fdselectpoll_pollobjregisterPOLLIN_piper_eventqr _sys_proc_fun_default_proc_funr _read_freq _threshold_timeout _coalesceset _eventsetr watch_managerdefault_proc_fun read_freq thresholdtimeoutrrrr 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(rrrrrryszNotifier.append_eventcCs|jSr()r*r rrrrszNotifier.proc_funTcCs||_|s|jdS)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.r0clear)r Zcoalescerrrcoalesce_eventsszNotifier.coalesce_eventsc Csz|dur|j}|j|}Wqjtjyd}z,|jdtjkrNWYd}~qnWYd}~qd}~00qjq|r|jd|ddkrdS|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"rargsr$ZEINTRr'r&)r r6r=rrrr check_eventsszNotifier.check_eventsc Csbtddg}t|jtj|ddkr*dS|d}||jkrTtd|j||jdSzt |j|}Wn,t y}zt |WYd}~n d}~00td|d}||kr^d}t d ||||\}}} } t d | |||||| \} | } t||| | } |jrDt| }||jvrP|j||j| n |j| ||| 7}qdS) 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)arrayfcntlZioctlr!termiosZFIONREADr,rOrr"read Exceptionrstructunpackdecoderr.r,r0addr(r)r Zbuf_Z queue_sizerUrZrsumZs_sizer5r1rZ fname_lenZbnameunamerZ raweventstrrrr read_eventssB        zNotifier.read_eventscCs|jr|j}|jjr,tdt|q|j|j}|durh|j t @sh|j t @st dt|q| |}|r|jr||q||q|j |jr|jdS)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_eventsrOrrrr5r1rsrtrr)rr*rr.r0r7)r rrZreventrrrprocess_eventss&       zNotifier.process_eventsc sdur4d}tjtjdp d}tj||ddkrXtjrXd}t|fdd }|dkrtjtj Btj Btj B} t | d } t | tttd tt| tfd 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.cst}|dkrJtt}|dkr>tdtdqTtdn tdttj}t|dttj tj Bd}t|dttj tj Bd}t|ddS)Nr/r rfrg) r"forksetsidchdirumask_exitrVO_RDONLYdup2r r )pidZfd_inpZfd_outZfd_err)stderrstdinrrr fork_daemons      z)Notifier.__daemonize..fork_daemonr r^cs tSr()r"unlinkr)pid_filerrr~6rz&Notifier.__daemonize..)r"rWbasenamerBargvrXlexistsrr r rrrVr_rr,getpidrrratexitr%) r rXrUrrTdirnamerYrrVrZfd_pidr)rXrTrUrrZ __daemonizes" zNotifier.__daemonizecCsB|jdkr>t}|j||}|dkr>td|t|dS)NrzNow sleeping %d seconds)r+rrOrsleep)r ref_timeZcur_timeZ sleep_amountrrr_sleep8s   zNotifier._sleepFcKs|r|jfi|zF||dur6||dur6Wq~t}|rX|||WqtyztdYq~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__daemonizerIrr:rarFKeyboardInterruptrOrstop)r callbackZ daemonizer9r`rrrloopAs     z Notifier.loopcCs4|jdur*|j|jt|jd|_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 rrr8r:rFrIr"devnullrbrarfrdrrrrr<s  8   +  8 .rc@s2eZdZdZd ddZddZdd 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) rThreadr r _stop_eventrr"piper'r$r%r"r&r1rrrr s    zThreadedNotifier.__init__cCsh|jt|jddtj|t ||j |jdt |jdt |jddS)zK Stop notifier's loop. Stop notification. Join the thread. rfsstoprN) rkr/r"r_r'rrjrXrrdr$rgrr rrrrds   zThreadedNotifier.stopcCs:|js6|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)rkisSetrIrr:rarF)r r`rrrrfs  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 rrrrunszThreadedNotifier.run)NrrN)rrrrr rdrfrnrrrrri}s & ric@s"eZdZdZdddZddZdS) 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 asyncorefile_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_readszAsyncNotifier.handle_read)NrrNN)rrrrr rsrrrrros  roc@s*eZdZdZd ddZddZdd ZdS) TornadoAsyncNotifierz" Tornado ioloop adapter. Nrc Cs8||_||_t||||||||j|j|jdS)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_loophandle_read_callbackrr Z add_handlerr!rsZREAD) r r2Ziolooprer3r4r5r6rrrrrr s  zTornadoAsyncNotifier.__init__cCs|j|jt|dSr()ruZremove_handlerr!rrdr rrrrdszTornadoAsyncNotifier.stopcOs(|||jdur$||dS)z0 See comment in AsyncNotifier. NrFrIrvr r9kwargsrrrrss z TornadoAsyncNotifier.handle_read)NNrrNNrrrrr rdrsrrrrrts rtc@s*eZdZdZd ddZddZdd ZdS) AsyncioNotifierz0 asyncio/trollius event loop adapter. NrcCs4||_||_t||||||||j|jdS)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|jt|dSr()rfZ remove_readerr!rrdr rrrrd7szAsyncioNotifier.stopcOs(|||jdur$||dSr(rwrxrrrrs;s zAsyncioNotifier.handle_read)NNrrNrzrrrrr{s  r{c@s$eZdZdZdZddZddZdS)WatchzE Represent a watch, i.e. a file or directory being watched. )r5rWr1rrrrcCs8||_||_||_||_||_||_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) r5rWr1rrrr"rr)r r5rWr1rrrrrrr JszWatch.__init__csDdfddjD}dtdtjj|tdf}|S)zE @return: String representation. @rtype: str  c s<g|]4}|dsdt|tdtt|fqS)rz%s%s%sr)rDrrrrr).0rTr rr js z"Watch.__repr__..z %s%s %s %srr)rX __slots__rrrrrr rrr rrbes  zWatch.__repr__N)rrrrrr rbrrrrr|Bsr|c@s0eZdZdZddZddZddZdd Zd S) ExcludeFilterz/ ExcludeFilter is an exclusion filter. cCsTt|tr||}nt|tr&|}ntg|_|D]}|jt|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_lregexrrecompileUNICODE)r Zarg_lstlstregexrrrr {s   zExcludeFilter.__init__cCsbg}t|d@}|D]&}|}|r|dr4q||qWdn1sT0Y|S)NrU#)rV readlinesstriprDr)r rrr[linepatternrrrrs  *z&ExcludeFilter._load_patterns_from_filecCs||duSr()match)r rrWrrr_matchszExcludeFilter._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)rr)r rWrrrrrs  zExcludeFilter.__call__N)rrrrr rrrrrrrrws  rc@seZdZdZddZdS)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 rrrrrr szWatchManagerError.__init__Nr rrrrrsrc@seZdZdZddfddZddZdd Zd d Zd d Ze ddZ ddZ ddZ ddZ d0ddZddZd1ddZdd 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. cCsdSrrrWrrrr~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 rrrrrr s     zWatchManager.__init__cCst|jdS)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 rrrrs 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 )rr)r r5rrrrszWatchManager.get_watchc CsHz |j|=Wn6tyB}ztdt|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)rKeyErrorrOrr,)r r5rrrrrs zWatchManager.del_watchcCs|jS)z Get a reference on the internal watch manager dictionary. @return: Internal watch manager dictionary. @rtype: dict )rr rrrrszWatchManager.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|<td||S)z Add a watch on path, build a Watch object and insert it in the watch manager dictionary. Return the wd value. r)r5rWr1rrrzNew %s) _WatchManager__format_pathrorr2r!r|rrOr)r rWr1rrrr5ZwatchrrrZ __add_watch!s     zWatchManager.__add_watchcCs|rt|S|gSdSr()globZiglob)r rWdo_globrrrZ__glob3s zWatchManager.__globNFTc  Csi} |dur|j}||D]} t| ts4d| |<q|| |D]x} || |D]f} || s|| ||||} | | <| dkrd| | |jf}|rt |qt || 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} Nrz$add_watch: cannot watch %s WD=%d, %s) r_WatchManager__format_paramr+r,_WatchManager__glob_WatchManager__walk_rec_WatchManager__add_watchrr'rOrr)r rWr1rrrrquietrret_ZnpathapathZrpathr5rrrrr9s4/    zWatchManager.add_watchccs|D]}||}|dur|Vnqtj|s2qtj|}t|}|jD]Z}|dj}tj||g}|tj kst||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"rWrrrrr commonprefixrr5)r ZlpathrrootZlendiwdZcurZprefrrrZ __get_sub_recs$       zWatchManager.__get_sub_reccCs||}|r||}i}|D]} || } | r:| dkr\d| } |rRt| q t| ||r|j|j| |} | dkrd|| <d| | |j f} |rt| q t| || | ksJ|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_recrrOrrrr2r!r'rrrr)r r5r1rrrrlwdrawdrrwd_rrrr update_watchsF           zWatchManager.update_watchccs&t|tr|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_params  zWatchManager.__format_paramcCs8||}|jD]}|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)rrrrW)r rWrrrrrs 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)rrrW)r r5rrrrrs 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"rWislinkrwalk)r toprrdirsfilesrrrZ __walk_rec s zWatchManager.__walk_recc Cs||}|r||}i}|D]~}|j|j|}|dkrpd||<d||jf}|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) rrrr6r!r'rOrrrrr) r r5rrrrrrrrrrrm_watch2s(      zWatchManager.rm_watchc sbtj|}|dkriStj||ttBO}fdd}|j|||t|dddddddS) 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(). rcst|ddurdS|jkS)NryF)rry)rrYrrcmp_name|sz3WatchManager.watch_transient_file..cmp_name)rFcSsdSrrrrrrr~rz3WatchManager.watch_transient_file..)rrrrr)r"rWr^rYrorprr)r rr1Z proc_classr^rrrrwatch_transient_file]s     z!WatchManager.watch_transient_filecCs|jSr(rr rrrget_ignore_eventsszWatchManager.get_ignore_eventscCs ||_dSr(r)r r`rrrset_ignore_eventsszWatchManager.set_ignore_eventsz'Make watch manager ignoring new events.)NFFFTN)NNFFT)FT)rrrrr rr rrrcrrrrrrrrrrrrrrrrHrrrrrs<      R# H   +)rc@sBeZdZdZdddZddZddZd d Zd d Zd dZ dS)RawOutputFormatz( Format string representations. NcCs|pi|_dSr()format)r rrrrr szRawOutputFormat.__init__cCs2t|tst|}|j|d||jddS)Nrnormal)r+r,rr)r rZ attributerrrrs   zRawOutputFormat.simplecCs ||dS)zPunctuation color.rrrrrrrszRawOutputFormat.punctuationcCs ||dS)zField value color.purplerrrrrrszRawOutputFormat.field_valuecCs ||dS)zField name color.bluerrrrrrszRawOutputFormat.field_namecCs|jdd||dS)zClass name color.redrbold)rrrrrrrrszRawOutputFormat.class_name)N) rrrrr rrrrrrrrrrs rc@seZdZdZddZdS)ColoredOutputFormatz0 Format colored string representations. c Cs.ddddddddd d d d d }t||dS)Nzzzzzzzzzzzz) rZblackrZgreenrrrZcyanrZulineZblinkinvert)rr )r frrrr s zColoredOutputFormat.__init__Nr rrrrrsrcCs<ttdttD] }|drtt|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. rZIN_TN)rrerglobalsrDr)Zevnamerrrcompatibility_modes   rc 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 |\}jrtd.jrtt j st a t |d/krd0}n|}t}jr>t|td1d2}nt|td3}d}jrjd4}|D]2} tj| d} | r|| O}n|d5| qhnt}d6} jrd7d8} | } jr҇fd9d8} | } td:||j||jjjd;|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_trueverbosez Verbose mode)actiondesthelpz-rz --recursive recursivez Add watches recursively on pathsz-az --auto_addrz,Automatically add watches on new directoriesz-gz--globrzTreat 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))metavarrrz-sz--statsrzDisplay dummy statisticsz-Vz --versionr zPyinotify versionz-fz --raw-format raw_formatzDisable enhanced output format.z-cz --commandstorecommandzShell command to run upon event rfz/tmp)r3r4)r3,z4The event '%s' specified with option -e is not validNcSsNtjt|tjdtjt|tjdtjdS)Nr^)rBrr_rrr,rrrrrcb$ s   zcommand_line..cbcstjjdddS)NT)shell) subprocessPopenrroptionsrrr. sz2Start monitoring %s, (press c^c to halt pyinotify))rrr)re)!ZoptparserZ add_option parse_argsrrOrNr print __version__rrrrrrrrrrrre ALL_FLAGSrrrrrrrrrrf) rrparserr9rWrrr1rr ZevcodeZcb_funrrrr command_lines                 r__main__)Wrr@rrrB version_infor rr"r"rAr=r$r>r<rMr] collectionsrrrrrrprrr functoolsr ImportErrorrZ ctypes.utilr __author__rrrrrrrPrOrQattrnamerrerrwr{rZflagcZvalcrrryvalrvrrrrrrrrrrrrrrrjrirqrortr{r|rrrrrrrrrrrrrs         .%< 2s     +$. +Q]U CY*%5<Oe