o npU[@sdZGdddeZGdddeZddlZejdkr eejddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlmZdd lmZmZddlZddlZddlZddlZddlZddlZzdd lmZWn eyYnwz ddlZddlZWn eydZYnwzddl Z Wn eydZ Ynwd 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]$\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@dAdAZMGdBdCdCZNGdDdEdEeZOGdFdGdGZPGdHdIdIZQeQaRGdJdKdKeQZSdLdMZTdNdOZUeVdPkreUdSdS)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/dist-packages/pyinotify.pyrsrc@eZdZdZddZdS)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 $ r N)r)deque)datetime timedelta)reducez#seb@dbzteam.org (Sebastien Martini)z0.9.6Fc@r)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__Nrrrrrrhrrc@sDeZdZdZeddZddZddZdd Zd d Z d d Z dS)INotifyWrapperz_ Abstract class wrapping access to inotify's functions. This is an internal class. cCs4tr t}|r |Strt}|r|SdSdS)zO Factory method instanciating and returning the right wrapper. N)ctypes_CtypesLibcINotifyWrapperinitinotify_syscalls_INotifySyscallsWrapper)inotifyrrrcreatevszINotifyWrapper.createcC|S)z< Return None is no errno code is available. ) _get_errnor rrr get_errnoszINotifyWrapper.get_errnocCs,|}|dur dSdt|tj|fS)NzErrno: no errno supportz Errno=%s (%s))r$osstrerrorerrno errorcode)r coderrr str_errnoszINotifyWrapper.str_errnocCr!N) _inotify_initr#rrr inotify_initzINotifyWrapper.inotify_initcCst|tsJ||||Sr+) isinstancestr_inotify_add_watchr fdpathnamemaskrrrinotify_add_watchsz INotifyWrapper.inotify_add_watchcCs |||Sr+)_inotify_rm_watchr r3wdrrrinotify_rm_watch zINotifyWrapper.inotify_rm_watchN) rrrr staticmethodr r$r*r-r6r:rrrrrqs  rc@<eZdZddZddZddZddZd d Zd d Zd S)rcCs d|_dSr+ _last_errnor#rrrr s z _INotifySyscallsWrapper.__init__cCs tsJdS)NT)rr#rrrrsz_INotifySyscallsWrapper.initcC|jSr+r>r#rrrr"z"_INotifySyscallsWrapper._get_errnoc Cs>zt}W|Sty}z |j|_WYd}~dSd}~wwN)rr-IOErrorr'r?)r r3rrrrr,s z%_INotifySyscallsWrapper._inotify_initc CsDz t|||}W|Sty!}z |j|_WYd}~dSd}~wwrB)rr6rDr'r?)r r3r4r5r9rrrrr1sz*_INotifySyscallsWrapper._inotify_add_watchc CsBz t||}W|Sty }z |j|_WYd}~dSd}~wwrB)rr:rDr'r?)r r3r9retrrrrr7sz)_INotifySyscallsWrapper._inotify_rm_watchN rrrr rr"r,r1r7rrrrrs rc@r=)rcCsd|_d|_dSr+)_libc_get_errno_funcr#rrrr  z"_CtypesLibcINotifyWrapper.__init__c CstsJd}tjdrd}d}ztj|}Wn ttfy#Ynwtj|dd|_ tj |_ t |j drBt |j drBt |j dsDd Sg|j j _tj|j j _tjtjtjg|j j_tj|j j_tjtjg|j j_tj|j j_dS) NcfreebsdrT) use_errnor-r6r:F)rsysplatform startswithutil find_libraryOSErrorrDCDLLrGr$rHhasattrr-argtypesc_intrestypec_char_pc_uint32r6r:)r try_libc_name libc_namerrrrs6        z_CtypesLibcINotifyWrapper.initcCs|jsJ|Sr+)rHr#rrrr"s z$_CtypesLibcINotifyWrapper._get_errnocCs|jdusJ|jSr+)rGr-r#rrrr,s z'_CtypesLibcINotifyWrapper._inotify_initcCs6|jdusJ|t}t|}|j|||Sr+)rGencoderMgetfilesystemencodingrcreate_string_bufferr6r2rrrr1s z,_CtypesLibcINotifyWrapper._inotify_add_watchcCs|jdusJ|j||Sr+)rGr:r8rrrr7z+_CtypesLibcINotifyWrapper._inotify_rm_watchNrFrrrrrs rcCs:td}t}|td|||d|S)zInitialize logger instance. pyinotifyz0[%(asctime)s %(name)s %(levelname)s] %(message)s)logging getLogger StreamHandler setFormatter Formatter addHandlersetLevel)logconsole_handlerrrr logger_inits   rkc@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 rIzProcINotify.__init__cCsHttj|j|jd}t|WdS1swYdS)z Gets attribute's value. @return: stored value. @rtype: int @raise IOError: if corresponding file in /proc/sys cannot be read. rN)openr%pathjoinrmrnintreadline)r file_objrrrget_vals $zProcINotify.get_valcCsPttj|j|jd}|t|dWddS1s!wYdS)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)rqr%rrrsrmrnwriter0)r nvalrvrrrset_val&s"zProcINotify.set_valcCsd|j|fS)Nz<%s=%d>)rnrwr#rrr__repr__3szProcINotify.__repr__N) rrrrr rwr|propertyvaluer}rrrrrls rl)max_queued_eventsmax_user_instancesmax_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) IN_ACCESS IN_MODIFY IN_ATTRIBIN_CLOSE_WRITEIN_CLOSE_NOWRITEIN_OPEN IN_MOVED_FROM IN_MOVED_TO IN_CREATE IN_DELETEIN_DELETE_SELF IN_MOVE_SELFi i@i) IN_UNMOUNT IN_Q_OVERFLOW IN_IGNOREDiiii i@l) IN_ONLYDIRIN_DONT_FOLLOWIN_EXCL_UNLINK IN_MASK_ADDIN_ISDIR IN_ONESHOT)OP_FLAGS EVENT_FLAGS 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)rr ALL_VALUES)r5msnamerrrmasknames  zEventsCodes.masknameN)rrrrFLAG_COLLECTIONSrr<rrrrrDs:= rcCs||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_tplrrrr s z_Event.__init__cCsd}t|jdddD]1\}}|drq |dkr#tt||}n t|tr,|s,d}|dt |t d t |f7}q d t d t |j j|t d f}|S) zS @return: Generic event string representation. @rtype: str cS|dSNrrrrrrrrz!_Event.__repr__..key_r5z''z %s%s%s=z %s%s%s %s<>)sorted__dict__rrOhexgetattrr/r0 output_format field_name punctuation field_value class_name __class__r)r srorrrrr}s$    z_Event.__repr__cCst|Sr+)reprr#rrr__str__r.z_Event.__str__N)rrrrr r}rrrrrrs  rc@ 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)r9r5cookier)_strrstriprr ridebugr0)r r9r5rrdrrrr s z_RawEvent.__init__cCs|jdur t||_|jSr+)rrrr#rrrrs  z_RawEvent.__str__N)rrrrr rrrrrrs rc@r)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|_z|jr(tj tj |j |j|_ WdStj |j |_ WdSt yJ}z t|WYd}~dSd}~ww)zH Concretely, this is the raw event plus inferred infos. N)rr rrr5COMPATIBILITY_MODE event_namerr%rrabspathrsr4AttributeErrorrir)r rawrrrrr 7s zEvent.__init__Nrrrrrrs rc@r)ProcessEventErrorzD ProcessEventError Exception. Raised on ProcessEvent error. cCt||dS)zT @param err: Exception error description. @type err: string Nr rrrrr OzProcessEventError.__init__NrrrrrrKrrc@r) _ProcessEventz* Abstract processing event class. cCs|j|jt@}tj|}|durtd|t|d|d}|dur(||St|d|ddd}|dur=||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%08xprocess_ process_IN_rr) r5rrrgetrrsplitprocess_default)r event stripped_maskrmethrrr__call__[s   z_ProcessEvent.__call__cCs d|jjS)Nz<%s>)rrr#rrrr}~r;z_ProcessEvent.__repr__N)rrrrrr}rrrrrWs #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 s z_SysProcessEvent.__init__cCsdt}|j|jfD]%}t|D]}|||dtddkr.td||d||=qq dS)zh Cleanup (delete) old (>1mn) records contained in self._mv_cookie and self._mv. r)minuteszCleanup: deleting entry %srN) rnowrrlistkeysrrir)r date_cur_seqkrrrcleanupsz_SysProcessEvent.cleanupc CsB|jt@r|j|j}tj|j|j}|j r| |s|jj }|||j|j d|j |j d}| |}|dur|dkrtj|rztj ||j|d|_q)n"t d|j|tjtj |jtjj|jdsb|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)rrr9rrrrr%seplenwatchesvaluesrOrsrierrorr pardirendswithr)r rrrr dest_path src_path_lenrxrrrprocess_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). r5)rr5)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_watchr9)r revent_rrrprocess_IN_IGNORED.s z#_SysProcessEvent.process_IN_IGNOREDNcCsp|j|j}|jttB@r|j}nt|jt@}|j|j|j |j |d}t r+||d<|dur4| |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. )r9r5rrrdiris_dirN)rrr9r5rrr#boolrrrrrupdater)r rrrdir_rrrrr9s z _SysProcessEvent.process_defaultr+) rrrrr rr rrrrr"rrrrrrs   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||_|jdi|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 Nr)peventmy_init)r r)kargsrrrr fs zProcessEvent.__init__cKdS)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 ||}|st||SdSNF)r)rr)r r stop_chainingrrrrs    zProcessEvent.__call__cCr@r+)r)r#rrr nested_peventrAzProcessEvent.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)riwarningr rrrrrsz"ProcessEvent.process_IN_Q_OVERFLOWcCr,)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 Nrr1rrrrs zProcessEvent.process_defaultr+) rrrrr)r r*rr/rrrrrrr(Rs   r(c@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)rMstdout_out)r outrrrr*s zPrintAllEvents.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 ryN)r4rzr0flushr1rrrrs zPrintAllEvents.process_defaultr+rrrrr*rrrrrr2s  r2c@r) ChainIfTruezc Makes conditional chaining depending on the result of the nested processing instance. cCs ||_dSzJ Method automatically called from base class constructor. N_func)r funcrrrr*s zChainIfTrue.my_initcCs || Sr+r:r1rrrrr;zChainIfTrue.process_defaultNr7rrrrr8s r8c@sBeZdZdZddZddZddZdd Zd d Zdd dZ dS)StatszH Compute and display trivial statistics about processed events. cCst|_i|_t|_dSr9)time _start_time_stats threadingLock _stats_lockr#rrrr*s z Stats.my_initcCsZ|jz!|jd}|D]}|j|d}|d|j|<qW|jdS|jw)z$ Processes |event|. |rrN)rCacquirerrr@rrelease)r reventsrcountrrrrs  zStats.process_defaultcCs.|jz |jW|jS|jwr+)rCrEr@copyrFr#rrr _stats_copys  zStats._stats_copycCs|}tt|j}d}|dkrt|d}n@d|kr$dkr1nn d|d|df}n)d|kr;dkrJnn d|d|ddf}n|dkrZd|d|ddf}||d <g}t|d d d D]\}}|d t |t |fqjdt |j j d|f}|S)Nr<seciz %dmn%dseciQz%dh%dmnz%dd%dh ElapsedTimecSrrrrrrrr rz Stats.__repr__..rz %s=%sz<%s%s >)rJrtr>r?r0rrappendrrrrrrrs)r statselapsed elapsed_strlevrrrrrr}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_WRONLYO_CREAT O_NOFOLLOWO_EXCLrqrzbytesrlocalegetpreferredencodingclose)r filenamerr3rrrdumpsz Stats.dump-csp|}|sdSt|}||dttd|dfdd}dt|t| dd d }|S) Nrz%%-26s%%-%ds%%s@rcs>t|dtdt|dtd|ddfS)Nrr`rz%dyellow)rrrrtsimplerfmtunityrrr<'szStats.__str__..funcrycSrrrrrrrr+rzStats.__str__..r) rJmaxrrrrrsmaprr)r scalerOmr<rrrcrrs  z Stats.__str__N)r_) rrrrr*rrJr}r^rrrrrr=s  r=c@r) NotifierErrorz8 Notifier Exception. Raised on Notifier error. cCr)zW @param err: Exception string's description. @type err: string Nr rrrrr 4rzNotifierError.__init__Nrrrrrrj/ rjc@seZdZdZ  dddZddZdd 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||_ ||_ |dur0t|_ ||_||_||_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 )rCrCNF)rget_fd_fdselectpoll_pollobjregisterPOLLIN_piper_eventqr _sys_proc_fun_default_proc_funr2 _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)rurNr1rrrryszNotifier.append_eventcCr@r+)rwr#rrrrrAzNotifier.proc_funTcCs||_|s |jdSdS)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{r}clear)r coalescerrrcoalesce_eventsszNotifier.coalesce_eventsc Cs z|dur |j}|j|}Wntjy,}z|jdtjkr'WYd}~qd}~ww |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 TNrFr) rzrqrprorargsr'EINTRrtrs)r rrErrrr check_eventss  zNotifier.check_eventsc CsZtddg}t|jtj|ddkrdS|d}||jkr*td|j||jdSz t |j|}Wnt yC}zt |d}~wwtd|d}||krd}t d ||||\}}} } t d | |||||| \} | } t||| | } |jrt| }||jvr|j||j| n|j| ||| 7}||ksPdSdS) zN Read events from device, build _RawEvents, and enqueue them. irrrCNzF(fd: %d) %d bytes available to read but threshold is fixed to %d byteszEvent queue size: %driIIIz%ds)arrayfcntlioctlrntermiosFIONREADryrirr%read Exceptionrjstructunpackdecoderr{r0r}addrurN)r buf_ queue_sizerpr rsums_sizer9r5r fname_lenbnameunamer  raweventstrrrr read_eventssJ        zNotifier.read_eventscCs|jrL|j}|jjrtdt|q|j|j}|dur4|j t @s4|j t @s3t dt|q| |}|rD|jrD||n|||js|j |jr[|jdSdS)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)rupopleftr ignore_eventsrirrrr9r5rrr0rvrrwrr{r}r)r rrreventrrrprocess_eventss*       zNotifier.process_eventsc sdurd}tjtjdpd}tj||ddkr,tjr,d}t|fdd }|dkrotjtj Btj Btj B} t | d } t | tttd tt| tfd d dSdS)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/rr`z.pidFz-Cannot daemonize: pid file %s already exists.cst}|dkr%tt}|dkrtdtdn tdntdttj}t|dttj tj Bd}t|dttj tj Bd}t|ddS)Nr/rTrr) r%forksetsidchdirumask_exitrqO_RDONLYdup2rUrV)pidfd_inpfd_outfd_err)stderrstdinr3rr fork_daemons      z)Notifier.__daemonize..fork_daemonrTrycs tSr+)r%unlinkr)pid_filerrr6s z&Notifier.__daemonize..)r%rrbasenamerMargvrslexistsrjrUrVrWrXrqrzrYr0getpidrZr[r\atexitrr) r rrr3rdirnamerrrrfd_pidr)rrrr3r __daemonizes$ zNotifier.__daemonizecCsJ|jdkr!t}|j||}|dkr#td|t|dSdSdS)NrzNow sleeping %d seconds)rxr>rirsleep)r ref_timecur_time sleep_amountrrr_sleep8s  zNotifier._sleepFcKs|r |jdi| z#||dur||durWn"t}|r-|||Wnty<tdYnwq | 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 rNTzPyinotify stops monitoring.r) _Notifier__daemonizerr>rrrKeyboardInterruptrirstop)r callback daemonizerrrrrloopAs$    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)rnrq unregisterr%r\rvr#rrrros   z Notifier.stopNrrN)Tr+r-)rrrrr rrrrrrr%devnullrrrrrrrrrl<s" 8   +  8 .rlc@s6eZdZdZ  d 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) rAThreadr r _stop_eventrlr%pipertrqrrrorsr~rrrr s    zThreadedNotifier.__init__cCsh|jt|jddtj|t ||j |jdt |jdt |jddS)zK Stop notifier's loop. Stop notification. Join the thread. rsstoprN) rr|r%rzrtrArrsrlrrqrr\r#rrrrs   zThreadedNotifier.stopcCsF|js!|t}|r||||jrdSdS)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)risSetrr>rrr)r rrrrrs  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)rr#rrrruns zThreadedNotifier.runr)rrrrr rrrrrrrr}s & rc@s&eZdZdZ  dddZddZdS) 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)rlr asyncorefile_dispatcherrn)r rrrrr 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)rrr#rrr handle_reads zAsyncNotifier.handle_read)NrrNN)rrrrr rrrrrrs  rc@s0eZdZdZ   d 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_callbackrlr add_handlerrnrREAD) r riolooprrrrrrrrrr s  zTornadoAsyncNotifier.__init__cC|j|jt|dSr+)rremove_handlerrnrlrr#rrrrr_zTornadoAsyncNotifier.stopcOs,|||jdur||dSdS)z0 See comment in AsyncNotifier. Nrrrr rkwargsrrrrs  z TornadoAsyncNotifier.handle_read)NNrrNNrrrrr rrrrrrrs  rc@s.eZdZdZ  d 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)rrrlr add_readerrnr)r rrrrrrrrrrr #s  zAsyncioNotifier.__init__cCrr+)r remove_readerrnrlrr#rrrr7r_zAsyncioNotifier.stopcOs,|||jdur||dSdSr+rrrrrr;s  zAsyncioNotifier.handle_read)NNrrNrrrrrrs  rc@s$eZdZdZdZddZddZdS)WatchzE Represent a watch, i.e. a file or directory being watched. )r9rrr5rrrr#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) r9rrr5rrrr%rr#)r r9rrr5rrrrrrr JszWatch.__init__csDdfddjD}dtdtjj|tdf}|S)zE @return: String representation. @rtype: str  c s<g|]}|dsdt|tdtt|fqS)rz%s%s%sr)rOrrrrr).0ror#rr js   z"Watch.__repr__..z %s%s %s %srr)rs __slots__rrrrrr rrr#rr}es  zWatch.__repr__N)rrrrrr r}rrrrrBs  rc@s0eZdZdZddZddZddZdd Zd S) ExcludeFilterz/ ExcludeFilter is an exclusion filter. cCsTt|tr ||}n t|tr|}ntg|_|D] }|jt|tj qdS)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/r0_load_patterns_from_filer TypeError_lregexrNrecompileUNICODE)r arg_lstlstregexrrrr {s   zExcludeFilter.__init__cCsdg}t|d!}|D]}|}|r|drq ||q Wd|S1s+wY|S)Nrp#)rq readlinesstriprOrN)r r]rrvlinepatternrrrrs    z&ExcludeFilter._load_patterns_from_filecCs||duSr+)match)r rrrrrr_matchzExcludeFilter._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 rrrrrrrs  zExcludeFilter.__call__N)rrrrr rrrrrrrrws  rc@r)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)wmdrr )r r rrrrr szWatchManagerError.__init__Nrrrrrrrkrc@seZdZdZddfddZddZdd Zd d Zd d Ze ddZ ddZ ddZ ddZ   d0ddZddZ  d1ddZdd 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. cCr,r-rrrrrrrzWatchManager.cCs\d|_||_i|_t|_|jdurt|j|_|jdkr,d}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-rnrRr*)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%r\rnr#rrrr\s zWatchManager.closecCr@)zs Return assigned inotify's file descriptor. @return: File descriptor. @rtype: int )rnr#rrrrmszWatchManager.get_fdcCs |j|S)zz Get watch from provided watch descriptor wd. @param wd: Watch descriptor. @type wd: int )rr)r r9rrrrs zWatchManager.get_watchc CsHz|j|=WdSty#}ztdt|WYd}~dSd}~ww)z Remove watch entry associated to watch descriptor wd. @param wd: Watch descriptor. @type wd: int z)Cannot delete unknown watch descriptor %sN)rKeyErrorrirr0)r r9rrrrr s  zWatchManager.del_watchcCr@)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%rrr )r rrrrr __format_paths zWatchManager.__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)r9rrr5rrrzNew %s) _WatchManager__format_pathrrr6rnrrrir)r rrr5rrrr9watchrrr __add_watch!s     zWatchManager.__add_watchcCs|rt|S|gSr+)globiglob)r rrdo_globrrr__glob3s zWatchManager.__globNFTc  Csi} |dur |j}||D]O} t| tsd| |<q|| |D]<} || |D]3} || sW|| ||||} | | <| dkrVd| | |jf}|rQt |q(t || q(d| | <q(q 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/r0_WatchManager__glob_WatchManager__walk_rec_WatchManager__add_watchrr*rirr)r rrr5rrrrquietrret_npathapathrpathr9rrrrr9s:/     zWatchManager.add_watchccs|D]T}||}|dur|Vnqtj|sqtj|}t|}|jD]-}|dj}tj||g}|tj ksPt||krVt||krV||tj krV|dj Vq)qdS)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 Nr) get_pathr%rrrr rrr commonprefixrr9)r lpathrrootlendiwdcurprefrrr __get_sub_recs(      zWatchManager.__get_sub_reccCs||}|r ||}i}|D]n} || } | r| dkr.d| } |r)t| qt| ||r^|j|j| |} | dkrXd|| <d| | |j f} |rSt| qt| || | ks^J|sb|rg|j | } |rl|| _ |rq|| _ 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_recrrirrrr6rnr*rrrr)r r9r5rrrrlwdrawdrrwd_rrrr update_watchsF           zWatchManager.update_watchccs*t|tr|D]}|VqdS|VdS)z @param param: Parameter. @type param: string or int @return: wrap param. @rtype: list of type(param) N)r/r)r paramp_rrr__format_params   zWatchManager.__format_paramcCs8||}|jD]}|dj|kr|dSq dS)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 rrN)r rrrr)r rrr rrrrs  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)rrrr)r r9rrrrrs zWatchManager.get_pathccsH|rtj|stj|s|VdSt|D]\}}}|VqdS)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%rrislinkrwalk)r toprrdirsfilesrrr __walk_rec s  zWatchManager.__walk_recc Cs||}|r ||}i}|D]?}|j|j|}|dkr8d||<d||jf}|r3t|qt||||j vrA|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) rr$rr:rnr*rirrrrr) r r9rrr%rr&r'rrrrrm_watch2s(      zWatchManager.rm_watchc sbtj|}|dkr iStj||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|ddur dS|jkS)NrF)rr)rrrrcmp_name|s z3WatchManager.watch_transient_file..cmp_name)r<FcSr,r-rrrrrrrz3WatchManager.watch_transient_file..)rrrrr)r%rrrrrrrr8)r r]r5 proc_classrr4rr3rwatch_transient_file]s     z!WatchManager.watch_transient_filecCr@r+rr#rrrget_ignore_eventsrAzWatchManager.get_ignore_eventscCs ||_dSr+r7)r r{rrrset_ignore_eventss zWatchManager.set_ignore_eventsz'Make watch manager ignoring new events.)NFFFTN)NNFFT)FT)rrrrr r\rmrr r~rr rrrr$r(rrrrr2r6r8r9rrrrrrs>      R# H  +)rc@sBeZdZdZdddZddZddZd d Zd d Zd dZ dS)RawOutputFormatz( Format string representations. NcCs|pi|_dSr+)format)r r;rrrr rzRawOutputFormat.__init__cCs2t|ts t|}|j|d||jddS)Nrnormal)r/r0r;r)r r attributerrrrbs  zRawOutputFormat.simplecC ||dS)zPunctuation color.r<rbrrrrr zRawOutputFormat.punctuationcCr>)zField value color.purpler?rrrrrr@zRawOutputFormat.field_valuecCr>)zField name color.bluer?rrrrrr@zRawOutputFormat.field_namecCs|jdd||dS)zClass name color.redrbold)r;rrbrrrrrszRawOutputFormat.class_namer+) rrrrr rbrrrrrrrrr:s  r:c@r)ColoredOutputFormatz0 Format colored string representations. c Cs.ddddddddd d d d d }t||dS)Nzzzzzzzzzzzz) r<blackrCgreenrarBrAcyanrDulineblinkinvert)r:r )r frrrr s zColoredOutputFormat.__init__NrrrrrrErrEcCs<ttdttD]}|drtt|t|q dadS)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. rIN_TN)rrrglobalsrOr)evnamerrrcompatibility_modes  rPc sddlm}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 |\}jrutd.jr|tt j st a t |d/krd0}n|}t}jrt|td1d2}nt|td3}d}jrɈjd4}|D]} tj| d} | r|| O}q|d5| qnt}d6} jrd7d8} | } jrfd9d8} | } 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--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))metavarrVrWz-sz--statsrOzDisplay dummy statisticsz-Vz --versionr zPyinotify versionz-fz --raw-format raw_formatzDisable enhanced output format.z-cz --commandstorecommandzShell command to run upon event rz/tmp)rr)r,z4The event '%s' specified with option -e is not validNcSsNtjt|tjdtjt|tjdtjdS)Nry)rMr3rzrrr0r6rrrrcb$ s   zcommand_line..cbcstjjdddS)NT)shell) subprocessPopenr]raoptionsrrrb. sz2Start monitoring %s, (press c^c to halt pyinotify))rrr)r)!optparserQ add_option parse_argsrTrirhr print __version__r[rErrrrOrlr=r2rYrr ALL_FLAGSrrrr]rrrXrr r) rQrRparserrrrrrr5rYrSevcodecb_funrbrrfr command_lines                 rq__main__)Wrrrr rM version_infor rAr%rorrr'rrrbr collectionsrrrr>rrr rZrd functoolsr ImportErrorr ctypes.utilr __author__rlrrrrrrkrirlattrnamerNrrmrrrflagcvalcrr&rvalrrrrrrrrrr(r2r8r=rjrlrrrrrrrrrrr:rrErPrqrrrrrs         .%< 2s     +$. +Q]U CY*%5<O e