pax_global_header00006660000000000000000000000064133200610700014502gustar00rootroot0000000000000052 comment=288a2b01fd4a726dc68d960f8351630aee788a13 PyInotify-0.2.10/000077500000000000000000000000001332006107000135145ustar00rootroot00000000000000PyInotify-0.2.10/.coverage000066400000000000000000000024711332006107000153140ustar00rootroot00000000000000!coverage.py: This is a private format, don't read it directly!{"lines":{"/home/dustin/development/python/pyinotify/inotify/test_support.py":[1,2,3,4,5,7,9,11,13,14,16,17,19,21,22],"/home/dustin/development/python/pyinotify/inotify/adapters.py":[1,2,3,4,5,6,8,10,11,15,16,20,22,23,25,26,27,28,31,32,35,36,39,40,41,42,43,44,46,47,49,51,53,56,59,60,61,63,65,66,67,69,70,72,73,75,76,78,84,85,88,89,91,92,93,95,97,98,99,100,101,102,104,105,107,110,112,115,117,118,121,123,124,126,132,134,135,136,138,139,141,142,145,148,150,152,153,154,161,162,163,165,170,171,172,176,177,191,194,195,196,197,199,200,201,202,204,208,209,210,216,217,219,221,230,231,232,234,235,238,239,242,245,247,250,252,253,256,259,261,264,265,267,268,269,271,273,275,276,278,280,281,282,283,285,287,288,289,292,294,295,298,299,301,302,303,305,307,308,310,312,313,314,315,317,319,327,328],"/home/dustin/development/python/pyinotify/inotify/library.py":[8,1,2,4,5],"/home/dustin/development/python/pyinotify/inotify/calls.py":[1,2,4,6,8,11,12,18,25,32,33,37,39,40,41,43,45,46,47,49,51,52,53,55,56],"/home/dustin/development/python/pyinotify/inotify/__init__.py":[1],"/home/dustin/development/python/pyinotify/inotify/constants.py":[3,4,8,9,10,11,12,13,14,15,16,17,18,19,23,24,30,34,35,36,40,41,42,43,44,46,47,48,52,53,54,55,56,57,58,59,60,61,62,63,67,68,69,73,74,75,76,77]}}PyInotify-0.2.10/.gitignore000066400000000000000000000001411332006107000155000ustar00rootroot00000000000000/lib/ /bin/ /include/ /inotify.egg-info/ /.Python /build /dist *.pyc /vagrant/.vagrant .DS_Store PyInotify-0.2.10/.travis.yml000066400000000000000000000003461332006107000156300ustar00rootroot00000000000000language: python python: - "2.7" - "3.3" - "3.4" - "3.5" install: - pip install -r requirements.txt - pip install coveralls script: nosetests -s -v --with-coverage --cover-package=inotify after_success: - coveralls PyInotify-0.2.10/LICENSE000066400000000000000000000431511332006107000145250ustar00rootroot00000000000000GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {description} Copyright (C) {year} {fullname} This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. {signature of Ty Coon}, 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License.PyInotify-0.2.10/MANIFEST.in000066400000000000000000000001201332006107000152430ustar00rootroot00000000000000include inotify/resources/requirements.txt include inotify/resources/README.rst PyInotify-0.2.10/README.rst000077700000000000000000000000001332006107000223602inotify/resources/README.rstustar00rootroot00000000000000PyInotify-0.2.10/build.sh000077500000000000000000000000661332006107000151540ustar00rootroot00000000000000#!/bin/bash python setup.py sdist bdist_wheel upload PyInotify-0.2.10/dev/000077500000000000000000000000001332006107000142725ustar00rootroot00000000000000PyInotify-0.2.10/dev/test.py000077500000000000000000000023011332006107000156220ustar00rootroot00000000000000#!/usr/bin/env python2.7 import os.path import sys current_path = os.path.dirname(__file__) dev_path = os.path.abspath(os.path.join(current_path, '..')) sys.path.insert(0, dev_path) import logging import inotify.adapters _DEFAULT_LOG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' _LOGGER = logging.getLogger(__name__) def _configure_logging(): _LOGGER.setLevel(logging.DEBUG) ch = logging.StreamHandler() formatter = logging.Formatter(_DEFAULT_LOG_FORMAT) ch.setFormatter(formatter) _LOGGER.addHandler(ch) def _main(): # paths = [ # '/tmp', # ] # # i = Inotify(paths=paths) i = inotify.adapters.Inotify() i.add_watch('/tmp') try: for event in i.event_gen(): if event is not None: (header, type_names, path, filename) = event _LOGGER.info("WD=(%d) MASK=(%d) COOKIE=(%d) LEN=(%d) MASK->NAMES=%s " "FILENAME=[%s]", header.wd, header.mask, header.cookie, header.len, type_names, filename) finally: i.remove_watch('/tmp') if __name__ == '__main__': _configure_logging() _main() PyInotify-0.2.10/inotify/000077500000000000000000000000001332006107000151755ustar00rootroot00000000000000PyInotify-0.2.10/inotify/__init__.py000066400000000000000000000000271332006107000173050ustar00rootroot00000000000000__version__ = '0.2.10' PyInotify-0.2.10/inotify/adapters.py000066400000000000000000000316051332006107000173570ustar00rootroot00000000000000import logging import select import os import struct import collections import time from errno import EINTR import inotify.constants import inotify.calls # Constants. _DEFAULT_EPOLL_BLOCK_DURATION_S = 1 _HEADER_STRUCT_FORMAT = 'iIII' _DEFAULT_TERMINAL_EVENTS = ( 'IN_Q_OVERFLOW', 'IN_UNMOUNT', ) # Globals. _LOGGER = logging.getLogger(__name__) _INOTIFY_EVENT = collections.namedtuple( '_INOTIFY_EVENT', [ 'wd', 'mask', 'cookie', 'len', ]) _STRUCT_HEADER_LENGTH = struct.calcsize(_HEADER_STRUCT_FORMAT) _IS_DEBUG = bool(int(os.environ.get('DEBUG', '0'))) class EventTimeoutException(Exception): pass class TerminalEventException(Exception): def __init__(self, type_name, event): super(TerminalEventException, self).__init__(type_name) self.event = event class Inotify(object): def __init__(self, paths=[], block_duration_s=_DEFAULT_EPOLL_BLOCK_DURATION_S): self.__block_duration = block_duration_s self.__watches = {} self.__watches_r = {} self.__buffer = b'' self.__inotify_fd = inotify.calls.inotify_init() _LOGGER.debug("Inotify handle is (%d).", self.__inotify_fd) self.__epoll = select.epoll() self.__epoll.register(self.__inotify_fd, select.POLLIN) self.__last_success_return = None for path in paths: self.add_watch(path) def __get_block_duration(self): """Allow the block-duration to be an integer or a function-call.""" try: return self.__block_duration() except TypeError: # A scalar value describing seconds. return self.__block_duration def __del__(self): _LOGGER.debug("Cleaning-up inotify.") os.close(self.__inotify_fd) def add_watch(self, path_unicode, mask=inotify.constants.IN_ALL_EVENTS): _LOGGER.debug("Adding watch: [%s]", path_unicode) # Because there might be race-conditions in the recursive handling (see # the notes in the documentation), we recommend to add watches using # data from a secondary channel, if possible, which means that we might # then be adding it, yet again, if we then receive it in the normal # fashion afterward. if path_unicode in self.__watches: _LOGGER.warning("Path already being watched: [%s]", path_unicode) return path_bytes = path_unicode.encode('utf8') wd = inotify.calls.inotify_add_watch(self.__inotify_fd, path_bytes, mask) _LOGGER.debug("Added watch (%d): [%s]", wd, path_unicode) self.__watches[path_unicode] = wd self.__watches_r[wd] = path_unicode return wd def remove_watch(self, path, superficial=False): """Remove our tracking information and call inotify to stop watching the given path. When a directory is removed, we'll just have to remove our tracking since inotify already cleans-up the watch. """ wd = self.__watches.get(path) if wd is None: return _LOGGER.debug("Removing watch for watch-handle (%d): [%s]", wd, path) del self.__watches[path] self.remove_watch_with_id(wd) def remove_watch_with_id(self, wd, superficial=False): del self.__watches_r[wd] if superficial is False: _LOGGER.debug("Removing watch for watch-handle (%d).", wd) inotify.calls.inotify_rm_watch(self.__inotify_fd, wd) def _get_event_names(self, event_type): names = [] for bit, name in inotify.constants.MASK_LOOKUP.items(): if event_type & bit: names.append(name) event_type -= bit if event_type == 0: break assert event_type == 0, \ "We could not resolve all event-types: (%d)" % (event_type,) return names def _handle_inotify_event(self, wd): """Handle a series of events coming-in from inotify.""" b = os.read(wd, 1024) if not b: return self.__buffer += b while 1: length = len(self.__buffer) if length < _STRUCT_HEADER_LENGTH: _LOGGER.debug("Not enough bytes for a header.") return # We have, at least, a whole-header in the buffer. peek_slice = self.__buffer[:_STRUCT_HEADER_LENGTH] header_raw = struct.unpack( _HEADER_STRUCT_FORMAT, peek_slice) header = _INOTIFY_EVENT(*header_raw) type_names = self._get_event_names(header.mask) _LOGGER.debug("Events received in stream: {}".format(type_names)) event_length = (_STRUCT_HEADER_LENGTH + header.len) if length < event_length: return filename = self.__buffer[_STRUCT_HEADER_LENGTH:event_length] # Our filename is 16-byte aligned and right-padded with NULs. filename_bytes = filename.rstrip(b'\0') self.__buffer = self.__buffer[event_length:] path = self.__watches_r.get(header.wd) if path is not None: filename_unicode = filename_bytes.decode('utf8') yield (header, type_names, path, filename_unicode) buffer_length = len(self.__buffer) if buffer_length < _STRUCT_HEADER_LENGTH: break def event_gen( self, timeout_s=None, yield_nones=True, filter_predicate=None, terminal_events=_DEFAULT_TERMINAL_EVENTS): """Yield one event after another. If `timeout_s` is provided, we'll break when no event is received for that many seconds. """ # We will either return due to the optional filter or because of a # timeout. The former will always set this. The latter will never set # this. self.__last_success_return = None last_hit_s = time.time() while True: block_duration_s = self.__get_block_duration() # Poll, but manage signal-related errors. try: events = self.__epoll.poll(block_duration_s) except IOError as e: if e.errno != EINTR: raise if timeout_s is not None: time_since_event_s = time.time() - last_hit_s if time_since_event_s > timeout_s: break continue # Process events. for fd, event_type in events: # (fd) looks to always match the inotify FD. names = self._get_event_names(event_type) _LOGGER.debug("Events received from epoll: {}".format(names)) for (header, type_names, path, filename) \ in self._handle_inotify_event(fd): last_hit_s = time.time() e = (header, type_names, path, filename) for type_name in type_names: if filter_predicate is not None and \ filter_predicate(type_name, e) is False: self.__last_success_return = (type_name, e) return elif type_name in terminal_events: raise TerminalEventException(type_name, e) yield e if timeout_s is not None: time_since_event_s = time.time() - last_hit_s if time_since_event_s > timeout_s: break if yield_nones is True: yield None @property def last_success_return(self): return self.__last_success_return class _BaseTree(object): def __init__(self, mask=inotify.constants.IN_ALL_EVENTS, block_duration_s=_DEFAULT_EPOLL_BLOCK_DURATION_S): # No matter what we actually received as the mask, make sure we have # the minimum that we require to curate our list of watches. self._mask = mask | \ inotify.constants.IN_ISDIR | \ inotify.constants.IN_CREATE | \ inotify.constants.IN_DELETE self._i = Inotify(block_duration_s=block_duration_s) def event_gen(self, ignore_missing_new_folders=False, **kwargs): """This is a secondary generator that wraps the principal one, and adds/removes watches as directories are added/removed. If we're doing anything funky and allowing the events to queue while a rename occurs then the folder may no longer exist. In this case, set `ignore_missing_new_folders`. """ for event in self._i.event_gen(**kwargs): if event is not None: (header, type_names, path, filename) = event if header.mask & inotify.constants.IN_ISDIR: full_path = os.path.join(path, filename) if ( (header.mask & inotify.constants.IN_MOVED_TO) or (header.mask & inotify.constants.IN_CREATE) ) and \ ( os.path.exists(full_path) is True or ignore_missing_new_folders is False ): _LOGGER.debug("A directory has been created. We're " "adding a watch on it (because we're " "being recursive): [%s]", full_path) self._i.add_watch(full_path, self._mask) if header.mask & inotify.constants.IN_MOVED_FROM: _LOGGER.debug("A directory has been removed. We're " "being recursive, but it would have " "automatically been deregistered: [%s]", full_path) # The watch would've already been cleaned-up internally. self._i.remove_watch(full_path, superficial=True) elif header.mask & inotify.constants.IN_MOVED_FROM: _LOGGER.debug("A directory has been renamed. We're " "being recursive, but it would have " "automatically been deregistered: [%s]", full_path) self._i.remove_watch(full_path, superficial=True) elif header.mask & inotify.constants.IN_MOVED_TO: _LOGGER.debug("A directory has been renamed. We're " "adding a watch on it (because we're " "being recursive): [%s]", full_path) self._i.add_watch(full_path, self._mask) yield event @property def inotify(self): return self._i class InotifyTree(_BaseTree): """Recursively watch a path.""" def __init__(self, path, mask=inotify.constants.IN_ALL_EVENTS, block_duration_s=_DEFAULT_EPOLL_BLOCK_DURATION_S): super(InotifyTree, self).__init__(mask=mask, block_duration_s=block_duration_s) self.__root_path = path self.__load_tree(path) def __load_tree(self, path): _LOGGER.debug("Adding initial watches on tree: [%s]", path) paths = [] q = [path] while q: current_path = q[0] del q[0] paths.append(current_path) for filename in os.listdir(current_path): entry_filepath = os.path.join(current_path, filename) if os.path.isdir(entry_filepath) is False: continue q.append(entry_filepath) for path in paths: self._i.add_watch(path, self._mask) class InotifyTrees(_BaseTree): """Recursively watch over a list of trees.""" def __init__(self, paths, mask=inotify.constants.IN_ALL_EVENTS, block_duration_s=_DEFAULT_EPOLL_BLOCK_DURATION_S): super(InotifyTrees, self).__init__(mask=mask, block_duration_s=block_duration_s) self.__load_trees(paths) def __load_trees(self, paths): _LOGGER.debug("Adding initial watches on trees: [%s]", ",".join(map(str, paths))) found = [] q = paths while q: current_path = q[0] del q[0] found.append(current_path) for filename in os.listdir(current_path): entry_filepath = os.path.join(current_path, filename) if os.path.isdir(entry_filepath) is False: continue q.append(entry_filepath) for path in found: self._i.add_watch(path, self._mask) PyInotify-0.2.10/inotify/calls.py000066400000000000000000000027761332006107000166610ustar00rootroot00000000000000import logging import ctypes import inotify.library _LOGGER = logging.getLogger(__name__) _LIB = inotify.library.instance class InotifyError(Exception): def __init__(self, message, *args, **kwargs): self.errno = ctypes.get_errno() message += " ERRNO=(%d)" % (self.errno,) super(InotifyError, self).__init__(message, *args, **kwargs) def _check_zero(result): if result != 0: raise InotifyError("Call failed (should return zero): (%d)" % (result,)) return result def _check_nonzero(result): if result == 0: raise InotifyError("Call failed (should return nonzero): (%d)" % (result,)) return result def _check_nonnegative(result): if result == -1: raise InotifyError("Call failed (should not be -1): (%d)" % (result,)) return result inotify_init = _LIB.inotify_init inotify_init.argtypes = [] inotify_init.restype = _check_nonnegative inotify_add_watch = _LIB.inotify_add_watch inotify_add_watch.argtypes = [ ctypes.c_int, ctypes.c_char_p, ctypes.c_uint32] inotify_add_watch.restype = _check_nonnegative inotify_rm_watch = _LIB.inotify_rm_watch inotify_rm_watch.argtypes = [ctypes.c_int, ctypes.c_int] inotify_rm_watch.restype = _check_nonnegative if getattr(_LIB, 'errno', None) is not None: errno = _LIB.errno elif getattr(_LIB, 'err', None) is not None: errno = _LIB.err else: raise EnvironmentError("'errno' not found in library") PyInotify-0.2.10/inotify/constants.py000066400000000000000000000043101332006107000175610ustar00rootroot00000000000000## inotify_init1 flags. IN_CLOEXEC = 0o2000000 IN_NONBLOCK = 0o0004000 ## Supported events suitable for MASK parameter of INOTIFY_ADD_WATCH. IN_ACCESS = 0x00000001 IN_MODIFY = 0x00000002 IN_ATTRIB = 0x00000004 IN_CLOSE_WRITE = 0x00000008 IN_CLOSE_NOWRITE = 0x00000010 IN_OPEN = 0x00000020 IN_MOVED_FROM = 0x00000040 IN_MOVED_TO = 0x00000080 IN_CREATE = 0x00000100 IN_DELETE = 0x00000200 IN_DELETE_SELF = 0x00000400 IN_MOVE_SELF = 0x00000800 ## Helper events. IN_CLOSE = (IN_CLOSE_WRITE | IN_CLOSE_NOWRITE) IN_MOVE = (IN_MOVED_FROM | IN_MOVED_TO) ## All events which a program can wait on. IN_ALL_EVENTS = (IN_ACCESS | IN_MODIFY | IN_ATTRIB | IN_CLOSE_WRITE | IN_CLOSE_NOWRITE | IN_OPEN | IN_MOVED_FROM | IN_MOVED_TO | IN_CREATE | IN_DELETE | IN_DELETE_SELF | IN_MOVE_SELF) ## Events sent by kernel. IN_UNMOUNT = 0x00002000 # Backing fs was unmounted. IN_Q_OVERFLOW = 0x00004000 # Event queued overflowed. IN_IGNORED = 0x00008000 # File was ignored. ## Special flags. IN_ONLYDIR = 0x01000000 # Only watch the path if it is a directory. IN_DONT_FOLLOW = 0x02000000 # Do not follow a sym link. IN_MASK_ADD = 0x20000000 # Add to the mask of an already existing watch. IN_ISDIR = 0x40000000 # Event occurred against dir. IN_ONESHOT = 0x80000000 # Only send event once. MASK_LOOKUP = { 0o2000000: 'IN_CLOEXEC', 0o0004000: 'IN_NONBLOCK', ## Supported events suitable for MASK parameter of INOTIFY_ADD_WATCH. 0x00000001: 'IN_ACCESS', 0x00000002: 'IN_MODIFY', 0x00000004: 'IN_ATTRIB', 0x00000008: 'IN_CLOSE_WRITE', 0x00000010: 'IN_CLOSE_NOWRITE', 0x00000020: 'IN_OPEN', 0x00000040: 'IN_MOVED_FROM', 0x00000080: 'IN_MOVED_TO', 0x00000100: 'IN_CREATE', 0x00000200: 'IN_DELETE', 0x00000400: 'IN_DELETE_SELF', 0x00000800: 'IN_MOVE_SELF', ## Events sent by kernel. 0x00002000: 'IN_UNMOUNT', 0x00004000: 'IN_Q_OVERFLOW', 0x00008000: 'IN_IGNORED', ## Special flags. 0x01000000: 'IN_ONLYDIR', 0x02000000: 'IN_DONT_FOLLOW', 0x20000000: 'IN_MASK_ADD', 0x40000000: 'IN_ISDIR', 0x80000000: 'IN_ONESHOT', } PyInotify-0.2.10/inotify/library.py000066400000000000000000000002551332006107000172150ustar00rootroot00000000000000import ctypes import ctypes.util _FILEPATH = ctypes.util.find_library('c') if _FILEPATH is None: _FILEPATH = 'libc.so.6' instance = ctypes.cdll.LoadLibrary(_FILEPATH) PyInotify-0.2.10/inotify/resources/000077500000000000000000000000001332006107000172075ustar00rootroot00000000000000PyInotify-0.2.10/inotify/resources/README.rst000066400000000000000000000170041332006107000207000ustar00rootroot00000000000000|Build\_Status| |Coverage\_Status| ======== Overview ======== *inotify* functionality is available from the Linux kernel and allows you to register one or more directories for watching, and to simply block and wait for notification events. This is obviously far more efficient than polling one or more directories to determine if anything has changed. This is available in the Linux kernel as of version 2.6 . We've designed this library to act as a generator. All you have to do is loop, and you'll see one event at a time and block in-between. After each cycle (all notified events were processed, or no events were received), you'll get a *None*. You may use this as an opportunity to perform other tasks, if your application is being primarily driven by *inotify* events. By default, we'll only block for one-second on queries to the kernel. This may be set to something else by passing a seconds-value into the constructor as *block_duration_s*. **This project is unrelated to the *PyInotify* project that existed prior to this one (this project began in 2015). That project is defunct and no longer available.** ========== Installing ========== Install via *pip*:: $ sudo pip install inotify ======= Example ======= Code for monitoring a simple, flat path (see "Recursive Watching" for watching a hierarchical structure):: import inotify.adapters def _main(): i = inotify.adapters.Inotify() i.add_watch('/tmp') with open('/tmp/test_file', 'w'): pass for event in i.event_gen(yield_nones=False): (_, type_names, path, filename) = event print("PATH=[{}] FILENAME=[{}] EVENT_TYPES={}".format( path, filename, type_names)) if __name__ == '__main__': _main() Output:: PATH=[/tmp] FILENAME=[test_file] EVENT_TYPES=['IN_MODIFY'] PATH=[/tmp] FILENAME=[test_file] EVENT_TYPES=['IN_OPEN'] PATH=[/tmp] FILENAME=[test_file] EVENT_TYPES=['IN_CLOSE_WRITE'] ^CTraceback (most recent call last): File "inotify_test.py", line 18, in _main() File "inotify_test.py", line 11, in _main for event in i.event_gen(yield_nones=False): File "/home/dustin/development/python/pyinotify/inotify/adapters.py", line 202, in event_gen events = self.__epoll.poll(block_duration_s) KeyboardInterrupt Note that this works quite nicely, but, in the event that you don't want to be driven by the loop, you can also provide a timeout and then even flatten the output of the generator directly to a list:: import inotify.adapters def _main(): i = inotify.adapters.Inotify() i.add_watch('/tmp') with open('/tmp/test_file', 'w'): pass events = i.event_gen(yield_nones=False, timeout_s=1) events = list(events) print(events) if __name__ == '__main__': _main() This will return everything that's happened since the last time you ran it (artificially formatted here):: [ (_INOTIFY_EVENT(wd=1, mask=2, cookie=0, len=16), ['IN_MODIFY'], '/tmp', u'test_file'), (_INOTIFY_EVENT(wd=1, mask=32, cookie=0, len=16), ['IN_OPEN'], '/tmp', u'test_file'), (_INOTIFY_EVENT(wd=1, mask=8, cookie=0, len=16), ['IN_CLOSE_WRITE'], '/tmp', u'test_file') ] **Note that the event-loop will automatically register new directories to be watched, so, if you will create new directories and then potentially delete them, between calls, and are only retrieving the events in batches (like above) then you might experience issues. See the parameters for `event_gen()` for options to handle this scenario.** ================== Recursive Watching ================== There is also the ability to add a recursive watch on a path. Example:: i = inotify.adapters.InotifyTree('/tmp/watch_tree') for event in i.event_gen(): # Do stuff... pass This will immediately recurse through the directory tree and add watches on all subdirectories. New directories will automatically have watches added for them and deleted directories will be cleaned-up. The other differences from the standard functionality: - You can't remove a watch since watches are automatically managed. - Even if you provide a very restrictive mask that doesn't allow for directory create/delete events, the *IN_ISDIR*, *IN_CREATE*, and *IN_DELETE* flags will still be seen. ===== Notes ===== - **IMPORTANT:** Recursively monitoring paths is **not** a functionality provided by the kernel. Rather, we artificially implement it. As directory-created events are received, we create watches for the child directories on-the-fly. This means that there is potential for a race condition: if a directory is created and a file or directory is created inside before you (using the `event_gen()` loop) have a chance to observe it, then you are going to have a problem: If it is a file, then you will miss the events related to its creation, but, if it is a directory, then not only will you miss those creation events but this library will also miss them and not be able to add a watch for them. If you are dealing with a **large number of hierarchical directory creations** and have the ability to be aware new directories via a secondary channel with some lead time before any files are populated *into* them, you can take advantage of this and call `add_watch()` manually. In this case there is limited value in using `InotifyTree()`/`InotifyTree()` instead of just `Inotify()` but this choice is left to you. - *epoll* is used to audit for *inotify* kernel events. - **The earlier versions of this project had only partial Python 3 compatibility (string related). This required doing the string<->bytes conversions outside of this project. As of the current version, this has been fixed. However, this means that Python 3 users may experience breakages until this is compensated-for on their end. It will obviously be trivial for this project to detect the type of the arguments that are passed but there'd be no concrete way of knowing which type to return. Better to just fix it completely now and move forward.** - You may also choose to pass the list of directories to watch via the *paths* parameter of the constructor. This would work best in situations where your list of paths is static. - Calling `remove_watch()` is not strictly necessary. The *inotify* resources is automatically cleaned-up, which would clean-up all watch resources as well. ======= Testing ======= Call "test.sh" to run the tests:: $ ./test.sh test__cycle (tests.test_inotify.TestInotify) ... ok test__get_event_names (tests.test_inotify.TestInotify) ... ok test__international_naming_python2 (tests.test_inotify.TestInotify) ... SKIP: Not in Python 2 test__international_naming_python3 (tests.test_inotify.TestInotify) ... ok test__automatic_new_watches_on_existing_paths (tests.test_inotify.TestInotifyTree) ... ok test__automatic_new_watches_on_new_paths (tests.test_inotify.TestInotifyTree) ... ok test__cycle (tests.test_inotify.TestInotifyTree) ... ok test__renames (tests.test_inotify.TestInotifyTree) ... ok test__cycle (tests.test_inotify.TestInotifyTrees) ... ok ---------------------------------------------------------------------- Ran 9 tests in 12.039s OK (SKIP=1) .. |Build_Status| image:: https://travis-ci.org/dsoprea/PyInotify.svg?branch=master :target: https://travis-ci.org/dsoprea/PyInotify .. |Coverage_Status| image:: https://coveralls.io/repos/github/dsoprea/PyInotify/badge.svg?branch=master :target: https://coveralls.io/github/dsoprea/PyInotify?branch=master PyInotify-0.2.10/inotify/resources/requirements.txt000066400000000000000000000000051332006107000224660ustar00rootroot00000000000000nose PyInotify-0.2.10/inotify/test_support.py000066400000000000000000000005771332006107000203330ustar00rootroot00000000000000import os import logging import shutil import tempfile import contextlib _LOGGER = logging.getLogger(__name__) @contextlib.contextmanager def temp_path(): path = tempfile.mkdtemp() original_wd = os.getcwd() os.chdir(path) try: yield path finally: os.chdir(original_wd) if os.path.exists(path) is True: shutil.rmtree(path) PyInotify-0.2.10/requirements.txt000077700000000000000000000000001332006107000257522inotify/resources/requirements.txtustar00rootroot00000000000000PyInotify-0.2.10/setup.py000066400000000000000000000020261332006107000152260ustar00rootroot00000000000000import setuptools import os import inotify APP_PATH = os.path.dirname(inotify.__file__) with open(os.path.join(APP_PATH, 'resources', 'README.rst')) as f: _LONG_DESCRIPTION = f.read() with open(os.path.join(APP_PATH, 'resources', 'requirements.txt')) as f: _INSTALL_REQUIRES = list(map(lambda s: s.strip(), f.readlines())) _DESCRIPTION = \ "An adapter to Linux kernel support for inotify directory-watching." setuptools.setup( name='inotify', version=inotify.__version__, description=_DESCRIPTION, long_description=_LONG_DESCRIPTION, classifiers=[ ], keywords='inotify', author='Dustin Oprea', author_email='myselfasunder@gmail.com', url='https://github.com/dsoprea/PyInotify', license='GPL 2', packages=setuptools.find_packages(exclude=['tests']), include_package_data=True, zip_safe=False, install_requires=_INSTALL_REQUIRES, package_data={ 'inotify': [ 'resources/README.rst', 'resources/requirements.txt', ] } ) PyInotify-0.2.10/test.sh000077500000000000000000000000261332006107000150300ustar00rootroot00000000000000nosetests -s -v tests PyInotify-0.2.10/tests/000077500000000000000000000000001332006107000146565ustar00rootroot00000000000000PyInotify-0.2.10/tests/__init__.py000066400000000000000000000000001332006107000167550ustar00rootroot00000000000000PyInotify-0.2.10/tests/test_inotify.py000066400000000000000000000361551332006107000177620ustar00rootroot00000000000000# -*- coding: utf-8 -*- import os import unittest import inotify.constants import inotify.adapters import inotify.test_support try: unicode except NameError: _HAS_PYTHON2_UNICODE_SUPPORT = False else: _HAS_PYTHON2_UNICODE_SUPPORT = True class TestInotify(unittest.TestCase): def __init__(self, *args, **kwargs): self.maxDiff = None super(TestInotify, self).__init__(*args, **kwargs) def __read_all_events(self, i): events = list(i.event_gen(timeout_s=1, yield_nones=False)) return events @unittest.skipIf(_HAS_PYTHON2_UNICODE_SUPPORT is True, "Not in Python 3") def test__international_naming_python3(self): with inotify.test_support.temp_path() as path: inner_path = os.path.join(path, '新增資料夾') os.mkdir(inner_path) i = inotify.adapters.Inotify() i.add_watch(inner_path) with open(os.path.join(inner_path, 'filename'), 'w'): pass events = self.__read_all_events(i) expected = [ (inotify.adapters._INOTIFY_EVENT(wd=1, mask=256, cookie=0, len=16), ['IN_CREATE'], inner_path, 'filename'), (inotify.adapters._INOTIFY_EVENT(wd=1, mask=32, cookie=0, len=16), ['IN_OPEN'], inner_path, 'filename'), (inotify.adapters._INOTIFY_EVENT(wd=1, mask=8, cookie=0, len=16), ['IN_CLOSE_WRITE'], inner_path, 'filename'), ] self.assertEquals(events, expected) @unittest.skipIf(_HAS_PYTHON2_UNICODE_SUPPORT is False, "Not in Python 2") def test__international_naming_python2(self): with inotify.test_support.temp_path() as path: inner_path = os.path.join(unicode(path), u'新增資料夾') os.mkdir(inner_path) i = inotify.adapters.Inotify() i.add_watch(inner_path) with open(os.path.join(inner_path, u'filename料夾'), 'w'): pass events = self.__read_all_events(i) expected = [ (inotify.adapters._INOTIFY_EVENT(wd=1, mask=256, cookie=0, len=16), ['IN_CREATE'], inner_path, u'filename料夾'), (inotify.adapters._INOTIFY_EVENT(wd=1, mask=32, cookie=0, len=16), ['IN_OPEN'], inner_path, u'filename料夾'), (inotify.adapters._INOTIFY_EVENT(wd=1, mask=8, cookie=0, len=16), ['IN_CLOSE_WRITE'], inner_path, u'filename料夾'), ] self.assertEquals(events, expected) def test__cycle(self): with inotify.test_support.temp_path() as path: path1 = os.path.join(path, 'aa') os.mkdir(path1) path2 = os.path.join(path, 'bb') os.mkdir(path2) i = inotify.adapters.Inotify() i.add_watch(path1) with open('ignored_new_file', 'w'): pass with open(os.path.join(path1, 'seen_new_file'), 'w'): pass with open(os.path.join(path2, 'ignored_new_file'), 'w'): pass os.remove(os.path.join(path1, 'seen_new_file')) events = self.__read_all_events(i) expected = [ ( inotify.adapters._INOTIFY_EVENT(wd=1, mask=256, cookie=0, len=16), ['IN_CREATE'], path1, 'seen_new_file' ), ( inotify.adapters._INOTIFY_EVENT(wd=1, mask=32, cookie=0, len=16), ['IN_OPEN'], path1, 'seen_new_file' ), ( inotify.adapters._INOTIFY_EVENT(wd=1, mask=8, cookie=0, len=16), ['IN_CLOSE_WRITE'], path1, 'seen_new_file' ), ( inotify.adapters._INOTIFY_EVENT(wd=1, mask=512, cookie=0, len=16), ['IN_DELETE'], path1, 'seen_new_file' ) ] self.assertEquals(events, expected) # This can't be removed until *after* we've read the events because # they'll be flushed the moment we remove the watch. i.remove_watch(path1) with open(os.path.join(path1, 'ignored_after_removal'), 'w'): pass events = self.__read_all_events(i) self.assertEquals(events, []) def test__get_event_names(self): all_mask = 0 for bit in inotify.constants.MASK_LOOKUP.keys(): all_mask |= bit all_names = inotify.constants.MASK_LOOKUP.values() all_names = list(all_names) i = inotify.adapters.Inotify() names = i._get_event_names(all_mask) self.assertEquals(names, all_names) class TestInotifyTree(unittest.TestCase): def __init__(self, *args, **kwargs): self.maxDiff = None super(TestInotifyTree, self).__init__(*args, **kwargs) def __read_all_events(self, i): events = list(i.event_gen(timeout_s=1, yield_nones=False)) return events def test__cycle(self): with inotify.test_support.temp_path() as path: path1 = os.path.join(path, 'aa') os.mkdir(path1) path2 = os.path.join(path, 'bb') os.mkdir(path2) i = inotify.adapters.InotifyTree(path) with open('seen_new_file1', 'w'): pass with open(os.path.join(path1, 'seen_new_file2'), 'w'): pass with open(os.path.join(path2, 'seen_new_file3'), 'w'): pass os.remove(os.path.join(path, 'seen_new_file1')) os.remove(os.path.join(path1, 'seen_new_file2')) os.remove(os.path.join(path2, 'seen_new_file3')) os.rmdir(path1) os.rmdir(path2) events = self.__read_all_events(i) expected = [ (inotify.adapters._INOTIFY_EVENT(wd=1, mask=256, cookie=0, len=16), ['IN_CREATE'], path, 'seen_new_file1'), (inotify.adapters._INOTIFY_EVENT(wd=1, mask=32, cookie=0, len=16), ['IN_OPEN'], path, 'seen_new_file1'), (inotify.adapters._INOTIFY_EVENT(wd=1, mask=8, cookie=0, len=16), ['IN_CLOSE_WRITE'], path, 'seen_new_file1'), (inotify.adapters._INOTIFY_EVENT(wd=2, mask=256, cookie=0, len=16), ['IN_CREATE'], path1, 'seen_new_file2'), (inotify.adapters._INOTIFY_EVENT(wd=2, mask=32, cookie=0, len=16), ['IN_OPEN'], path1, 'seen_new_file2'), (inotify.adapters._INOTIFY_EVENT(wd=2, mask=8, cookie=0, len=16), ['IN_CLOSE_WRITE'], path1, 'seen_new_file2'), (inotify.adapters._INOTIFY_EVENT(wd=3, mask=256, cookie=0, len=16), ['IN_CREATE'], path2, 'seen_new_file3'), (inotify.adapters._INOTIFY_EVENT(wd=3, mask=32, cookie=0, len=16), ['IN_OPEN'], path2, 'seen_new_file3'), (inotify.adapters._INOTIFY_EVENT(wd=3, mask=8, cookie=0, len=16), ['IN_CLOSE_WRITE'], path2, 'seen_new_file3'), (inotify.adapters._INOTIFY_EVENT(wd=1, mask=512, cookie=0, len=16), ['IN_DELETE'], path, 'seen_new_file1'), (inotify.adapters._INOTIFY_EVENT(wd=2, mask=512, cookie=0, len=16), ['IN_DELETE'], path1, 'seen_new_file2'), (inotify.adapters._INOTIFY_EVENT(wd=3, mask=512, cookie=0, len=16), ['IN_DELETE'], path2, 'seen_new_file3'), (inotify.adapters._INOTIFY_EVENT(wd=2, mask=1024, cookie=0, len=0), ['IN_DELETE_SELF'], path1, ''), (inotify.adapters._INOTIFY_EVENT(wd=2, mask=32768, cookie=0, len=0), ['IN_IGNORED'], path1, ''), (inotify.adapters._INOTIFY_EVENT(wd=1, mask=1073742336, cookie=0, len=16), ['IN_ISDIR', 'IN_DELETE'], path, 'aa'), (inotify.adapters._INOTIFY_EVENT(wd=3, mask=1024, cookie=0, len=0), ['IN_DELETE_SELF'], path2, ''), (inotify.adapters._INOTIFY_EVENT(wd=3, mask=32768, cookie=0, len=0), ['IN_IGNORED'], path2, ''), (inotify.adapters._INOTIFY_EVENT(wd=1, mask=1073742336, cookie=0, len=16), ['IN_ISDIR', 'IN_DELETE'], path, 'bb'), ] self.assertEquals(events, expected) def test__renames(self): # Since we're not reading the events one at a time in a loop and # removing or renaming folders will flush any queued events, we have to # group things in order to check things first before such operations. with inotify.test_support.temp_path() as path: i = inotify.adapters.InotifyTree(path) old_path = os.path.join(path, 'old_folder') new_path = os.path.join(path, 'new_folder') os.mkdir(old_path) events1 = self.__read_all_events(i) expected = [ (inotify.adapters._INOTIFY_EVENT(wd=1, mask=1073742080, cookie=events1[0][0].cookie, len=16), ['IN_ISDIR', 'IN_CREATE'], path, 'old_folder'), ] self.assertEquals(events1, expected) os.rename(old_path, new_path) events2 = self.__read_all_events(i) expected = [ (inotify.adapters._INOTIFY_EVENT(wd=1, mask=1073741888, cookie=events2[0][0].cookie, len=16), ['IN_MOVED_FROM', 'IN_ISDIR'], path, 'old_folder'), (inotify.adapters._INOTIFY_EVENT(wd=1, mask=1073741952, cookie=events2[1][0].cookie, len=16), ['IN_MOVED_TO', 'IN_ISDIR'], path, 'new_folder'), ] self.assertEquals(events2, expected) with open(os.path.join(new_path, 'old_filename'), 'w'): pass os.rename( os.path.join(new_path, 'old_filename'), os.path.join(new_path, 'new_filename')) os.remove(os.path.join('new_folder', 'new_filename')) os.rmdir('new_folder') events3 = self.__read_all_events(i) expected = [ (inotify.adapters._INOTIFY_EVENT(wd=3, mask=256, cookie=0, len=16), ['IN_CREATE'], new_path, 'old_filename'), (inotify.adapters._INOTIFY_EVENT(wd=3, mask=32, cookie=0, len=16), ['IN_OPEN'], new_path, 'old_filename'), (inotify.adapters._INOTIFY_EVENT(wd=3, mask=8, cookie=0, len=16), ['IN_CLOSE_WRITE'], new_path, 'old_filename'), (inotify.adapters._INOTIFY_EVENT(wd=3, mask=64, cookie=events3[3][0].cookie, len=16), ['IN_MOVED_FROM'], new_path, 'old_filename'), (inotify.adapters._INOTIFY_EVENT(wd=3, mask=128, cookie=events3[4][0].cookie, len=16), ['IN_MOVED_TO'], new_path, 'new_filename'), (inotify.adapters._INOTIFY_EVENT(wd=3, mask=512, cookie=0, len=16), ['IN_DELETE'], new_path, 'new_filename'), (inotify.adapters._INOTIFY_EVENT(wd=3, mask=1024, cookie=0, len=0), ['IN_DELETE_SELF'], new_path, ''), (inotify.adapters._INOTIFY_EVENT(wd=3, mask=32768, cookie=0, len=0), ['IN_IGNORED'], new_path, ''), (inotify.adapters._INOTIFY_EVENT(wd=1, mask=1073742336, cookie=0, len=16), ['IN_ISDIR', 'IN_DELETE'], path, 'new_folder'), ] self.assertEquals(events3, expected) def test__automatic_new_watches_on_new_paths(self): # Tests that watches are actively established as new folders are # created. with inotify.test_support.temp_path() as path: i = inotify.adapters.InotifyTree(path) path1 = os.path.join(path, 'folder1') path2 = os.path.join(path1, 'folder2') os.mkdir(path1) events = self.__read_all_events(i) expected = [ (inotify.adapters._INOTIFY_EVENT(wd=1, mask=1073742080, cookie=0, len=16), ['IN_ISDIR', 'IN_CREATE'], path, 'folder1'), ] self.assertEquals(events, expected) os.mkdir(path2) events = self.__read_all_events(i) expected = [ (inotify.adapters._INOTIFY_EVENT(wd=2, mask=1073742080, cookie=0, len=16), ['IN_ISDIR', 'IN_CREATE'], path1, 'folder2'), ] self.assertEquals(events, expected) with open(os.path.join(path2,'filename'), 'w'): pass events = self.__read_all_events(i) expected = [ (inotify.adapters._INOTIFY_EVENT(wd=3, mask=256, cookie=0, len=16), ['IN_CREATE'], path2, 'filename'), (inotify.adapters._INOTIFY_EVENT(wd=3, mask=32, cookie=0, len=16), ['IN_OPEN'], path2, 'filename'), (inotify.adapters._INOTIFY_EVENT(wd=3, mask=8, cookie=0, len=16), ['IN_CLOSE_WRITE'], path2, 'filename'), ] self.assertEquals(events, expected) def test__automatic_new_watches_on_existing_paths(self): # Tests whether the watches are recursively established when we # initialize. with inotify.test_support.temp_path() as path: path1 = os.path.join(path, 'folder1') path2 = os.path.join(path1, 'folder2') os.mkdir(path1) os.mkdir(path2) i = inotify.adapters.InotifyTree(path) with open(os.path.join(path2,'filename'), 'w'): pass events = self.__read_all_events(i) expected = [ (inotify.adapters._INOTIFY_EVENT(wd=3, mask=256, cookie=0, len=16), ['IN_CREATE'], path2, 'filename'), (inotify.adapters._INOTIFY_EVENT(wd=3, mask=32, cookie=0, len=16), ['IN_OPEN'], path2, 'filename'), (inotify.adapters._INOTIFY_EVENT(wd=3, mask=8, cookie=0, len=16), ['IN_CLOSE_WRITE'], path2, 'filename'), ] self.assertEquals(events, expected) class TestInotifyTrees(unittest.TestCase): def __init__(self, *args, **kwargs): self.maxDiff = None super(TestInotifyTrees, self).__init__(*args, **kwargs) def __read_all_events(self, i): events = list(i.event_gen(timeout_s=1, yield_nones=False)) return events def test__cycle(self): with inotify.test_support.temp_path() as path: path1 = os.path.join(path, 'aa') os.mkdir(path1) path2 = os.path.join(path, 'bb') os.mkdir(path2) i = inotify.adapters.InotifyTrees([path1, path2]) with open(os.path.join(path1, 'seen_new_file1'), 'w'): pass with open(os.path.join(path2, 'seen_new_file2'), 'w'): pass events = self.__read_all_events(i) expected = [ (inotify.adapters._INOTIFY_EVENT(wd=1, mask=256, cookie=0, len=16), ['IN_CREATE'], path1, 'seen_new_file1'), (inotify.adapters._INOTIFY_EVENT(wd=1, mask=32, cookie=0, len=16), ['IN_OPEN'], path1, 'seen_new_file1'), (inotify.adapters._INOTIFY_EVENT(wd=1, mask=8, cookie=0, len=16), ['IN_CLOSE_WRITE'], path1, 'seen_new_file1'), (inotify.adapters._INOTIFY_EVENT(wd=2, mask=256, cookie=0, len=16), ['IN_CREATE'], path2, 'seen_new_file2'), (inotify.adapters._INOTIFY_EVENT(wd=2, mask=32, cookie=0, len=16), ['IN_OPEN'], path2, 'seen_new_file2'), (inotify.adapters._INOTIFY_EVENT(wd=2, mask=8, cookie=0, len=16), ['IN_CLOSE_WRITE'], path2, 'seen_new_file2'), ] self.assertEquals(events, expected) PyInotify-0.2.10/tox.ini000066400000000000000000000001411332006107000150230ustar00rootroot00000000000000[tox] envlist = py27, py33, py34, py35 [testenv] deps = -rrequirements.txt commands = ./test.sh PyInotify-0.2.10/vagrant/000077500000000000000000000000001332006107000151565ustar00rootroot00000000000000PyInotify-0.2.10/vagrant/Vagrantfile000066400000000000000000000006621332006107000173470ustar00rootroot00000000000000# -*- mode: ruby -*- # vi: set ft=ruby : # Vagrantfile API/syntax version. Don't touch unless you know what you're doing! VAGRANTFILE_API_VERSION = "2" Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.vm.box = "ubuntu/trusty64" config.vm.synced_folder "..", "/inotify", mount_options: ["dmode=775,fmode=775"] config.vm.hostname = "test-linux.vagrant" config.vm.provision :shell, path: "bootstrap.sh" end PyInotify-0.2.10/vagrant/bootstrap.sh000066400000000000000000000001371332006107000175300ustar00rootroot00000000000000#!/bin/bash apt-get update apt-get install -y python-pip cd /inotify python setup.py develop