• Stars
    star
    240
  • Rank 167,275 (Top 4 %)
  • Language
    Python
  • License
    GNU General Publi...
  • Created over 10 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

An efficient and elegant inotify (Linux filesystem activity monitor) library for Python. Python 2 and 3 compatible.

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 <module>
    _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

It is possible to run tests using the setuptools test target:

$ python setup.py test

Or you can install nose and use that directly:

$ pip install nose

Then, 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)

More Repositories

1

GDriveFS

An innovative FUSE wrapper for Google Drive.
Python
663
star
2

go-exif

A very complete, highly tested, standards-driven (but customizable) EXIF reader/writer lovingly written in Go.
Go
491
star
3

PySvn

Lightweight Subversion library for Python.
Python
215
star
4

PyEasyArchive

A very intuitive and useful adapter to libarchive for universal archive access.
Python
97
star
5

go-jpeg-image-structure

Parse JPEG data into segments via code or CLI from pure Go. Read/export/write EXIF data. Read XMP and IPTC metadata.
Go
69
star
6

go-ext4

A pure Go implementation of an ext4 reader with journaling support that does not require the kernel nor privileged access.
Go
43
star
7

Snackwich

A Snack-based Python console UI that reads screen configurations from a file.
Python
27
star
8

TightOCR

A slim, non-SWIG Python adapter to CTesseract (Tesseract OCR for C).
Python
24
star
9

GeonamesRdf

A Python client for the RDF web-services provided by Geonames (http://www.geonames.org).
Python
22
star
10

go-png-image-structure

Read/write PNGs as well as the EXIF in PNGs from pure Go.
Go
22
star
11

go-perceptualhash

Blockhash perceptual-hash algorithm for images. Written in pure Go.
Go
21
star
12

PythonEtcdClient

A simple and efficient etcd client that exposes all functions and just works.
Python
21
star
13

M2CryptoWindows

Binaries for Python 2.7 M2Crypto under Windows
19
star
14

go-exfat

exFAT reader implementation based on Microsoft specifications.
Go
18
star
15

PySecure

A complete Python SSH/SFTP library based on libssh.
Python
18
star
16

go-exif-knife

Perform surgical operations on EXIF data at the command-line with JPG, PNG, HEIC, and TIFF files.
Go
17
star
17

RandomUtility

Disparate tools by published by Dustin.
Python
14
star
18

TinyUntar

A tiny untar library written in C.
C
14
star
19

GeditSafetySave

Automatically store unsaved documents to a temporary location under the current user's home. This keeps your documents, temporary to-do lists, etc.. safe from crashes.
Python
14
star
20

CTesseract

A C adapter for the C++ Tesseract OCR Library (Google).
C++
13
star
21

go-fuse-example

A minimal, browseable, read-only, memory-based filesystem in Go.
Go
12
star
22

RijndaelPbkdf

Pure-Python Rijndael and PBKDF2 package. Python2 and Python3 compatible.
Python
12
star
23

CodeMirrorRemoteValidator

An asynchronous CodeMirror lint plugin that will receive code, send it to a callback (that can send it somewhere via Ajax, etc..), and apply any discovered errors on return.
JavaScript
12
star
24

go-appengine-sessioncascade

Equip Go with session support under Google AppEngine. Implement one or more AppEngine-specific backends, such as Memcache and Datastore, to store your session data.
Go
12
star
25

go-heic-exif-extractor

Parses an HEIC image and returns an EXIF accessor (if an EXIF blob is present).
Go
11
star
26

youtube-autodownloader

Monitor YouTube playlists and automatically download newly-added videos.
Python
11
star
27

PyHdHomeRun

Python interface to HDHomeRun network-attached TV tuners.
Python
10
star
28

ChromeIdGenerator

A tiny tool to generate Google Chrome extension IDs from an extension's public-key.
Python
9
star
29

ApnsPlistCsr

Tool to produce encoded Plists/CSRs for APNS.
Python
9
star
30

PySchedules

Schedules Direct library for Python. Provides event-driven hooks for lineup, station, channel map, schedule, program, cast/crew, and genre data. Also provides QAM map (channels.conf) data. Go wild.
Python
9
star
31

protobufp

Adds the stream-processing to protobuf messaging that you usually need to add yourself.
Python
8
star
32

go-exiftool

List EXIF tags, set EXIF tags, and extract thumbnails in images using Go.
Go
7
star
33

PythonUpstart

An intuitive library interface to Upstart for service and job management.
Python
7
star
34

go-iptc

Parse IPTC metadata with pure Go
Go
6
star
35

JobX

JobExchange is a distributed Python-Based MapReduce solution.
Python
5
star
36

M2CryptoWin64

An installable M2Crypto Python package for 64-bit Windows systems.
Python
5
star
37

SslApi

An SOA certificate authority (CA).
Python
5
star
38

go-time-parse

Parse time phrases into Go durations.
Go
5
star
39

M2CryptoWin32

An installable M2Crypto Python package for 32-bit Windows systems.
Python
5
star
40

go-logging

Useful and awesome logging system for Go with prefixing and stacktraces.
Go
5
star
41

RestPipe

An SSL-authenticated, durable, bidirectional, RESTful, client-server pipe that transports custom events.
Python
5
star
42

ZapLib

A C library of uniform DVB tuning calls for ATSC (US), DVB-C (cable), DVB-S (satellite), DVB-T (terrestrial). Based on dvb-apps.
C
5
star
43

markdown-embedimages

Translate markdown to HTML and encode/embed images into the HTML.
Python
5
star
44

go-parallel-walker

CURRENTLY IN ACTIVE DEVELOPMENT - A simple, tuneable Go package and CLI tool to quickly walk a filesystem using a concurrently-processed job queue.
Go
4
star
45

RelayServer

A service that that acts as a single proxy between many individual clients and many instances of a server. As the clients initiate connections to the relay server, this solution defeats NAT.
Python
4
star
46

heic-exif-samples

Samples of HEIC images with EXIF. At this point in time they're non-trivial to find in the wild.
4
star
47

AwsDynDns

Update your Route53-hosted domain name with your public IP.
Python
4
star
48

CaKit

A light project that conveniently bundles the logic needed to build both example CA certificates and a signed, example certificate.
Python
4
star
49

DtcLookup

A webpage-based database for automotive diagnostic trouble codes (DTC's).
Python
4
star
50

time-to-go

Efficiently store, scan, retrieve, update, and add time-series blobs on a filesystem.
Go
4
star
51

YiiBash

Add Bash command completion to your PHP Yii project.
PHP
4
star
52

GlacierTool

A simple tool to do massive uploads to Amazon Glacier
Python
4
star
53

PyZap

Python wrapper for ZapLib digital television (DVB) tuning library.
Python
4
star
54

go-tiff-image-structure

Parse TIFF data for EXIF metadata
Go
4
star
55

JsonPare

A very simple utility to decode and unwind JSON into JSON from the command-line.
Python
4
star
56

SMARTOnFHIRExample

A working example of how to read FHIR health data from a SMART resource and plot aggregate vital signs (all patients).
Python
4
star
57

go-xmp

Parse XMP documents (for image-metadata) with pure Go.
Go
4
star
58

go-utility

Reusable tools.
Go
3
star
59

go-geographic-attractor

Efficiently identify the nearest major city to a given coordinate.
Go
3
star
60

python-googleautoauth

Dramatically reduces the complexity of the Google API authentication/authorization process in command-line tools.
Python
3
star
61

go-appengine-logging

Configuration-based AppEngine logging library with level control, filters, and pluggable, interface-based writers.
Go
3
star
62

go-geographic-index

An in-memory time-series index that can be populated manually and/or by recursively processing a path.
Go
3
star
63

go-gpx

Easily and efficiently processing GPX (geographic track/log) data from Go.
Go
3
star
64

go-time-index

A simple Go package to manage time-series with data and slices of time-intervals with data.
Go
3
star
65

go-geographic-autogroup-images

A package that knows how to take a list of locations, a list of images, knowledge of EXIF, and some geographic/population data (if any images are not already geotagged), and group images by the major cities that they were taken near.
Go
3
star
66

HuffmanExample

Shows how to build a tree, establish an encoding, encode the data, preorder-serialize the binary tree, combine the tree and data to render complete file-data, and reverse the process.
Python
3
star
67

go-s2

A tool that can convert between coordinates, S2 cells, and S2 tokens, print cell info, and generate KML visualizations of cell parents and boundaries.
Go
2
star
68

go-napster-to-spotify-sync

Install tracks from Napster favorites to a Spotify playlist by one or more artists.
Go
2
star
69

go-pathfingerprint

Recursively calculate a SHA1 or SHA256 hash for a given directory.
Go
2
star
70

PySynchronousGlacier

Execute synchronous workflows against Amazon Glacier.
Python
2
star
71

SvnCl

A one-line command to streamline building a Subversion changelog for tag/release messages.
Python
2
star
72

go-napster

A Go client for Napster/Rhapsody.
Go
2
star
73

TabManiac

Automatically back-up your Chrome tabs, and maintain a history of backups.
JavaScript
2
star
74

go-efficient-json-reader

Easily, efficiently, iteratively parse massive JSON data structures.
Go
2
star
75

RWebApplicationExample

An example Rook-based R web application
HTML
2
star
76

omsa-alert

Send emails or call commands when there are controller/disk problems reported by the Dell OMSA omreport command-line tool.
Python
2
star
77

bracketed-image-finder

Determine groups of images that were produced by bracketed image capture (e.g. Sony cameras)
Python
2
star
78

go-photoshop-info-format

Minimal Photoshop format implementation. Currently only provides parsing functionality to expose embedded IPTC data.
Go
2
star
79

PathScan

A parallellized filesystem scanning, filtering, and processing framework (iteration 3).
Python
2
star
80

go-webp-image-structure

Parse WEBP RIFF stream and expose EXIF data via pure Go.
Go
2
star
81

HookableWebServer

A tiny C++ (mostly C) web-server that calls function pointers for requests and logging. Based on IBM's open-source small "nweb" web server..
C++
2
star
82

RemoteImageBrowser

Allows you to efficiently browse a large image-file hierarchy from a website with thumbnails (cached) and lightboxes.
JavaScript
2
star
83

MpegTsScanner

Library to scan packets from an MPEG-TS file. Also provides a call to grab information on the first program found. This latter feature is useful for getting information (subtitle info, etc..) for a program recorded from an ATSC/DVB television tuner. Depends on the LIBDVBPSI library (from the VLC project).
C
2
star
84

go-github-reminders

A tool that determines what Github issues you are currently involved in and reminds you about issues you are overdue in responding to.
Go
2
star
85

LicensePrepend

Make sure all your source files have the standard licensing stub at the top.
Python
2
star
86

BeanTool

A console tool for querying a beanstalkd queue.
Python
2
star
87

WebsocketServer

A reference implementation for a WebSocket server and two sample clients. Tested under Firefox 13 and Chrome 20.
PHP
2
star
88

go-gpxreader

Easily and efficiently processing GPX (geographic track/log) data from Go. PROJECT IS DEPRECATED. PLEASE USE go-gpx/reader.
Go
2
star
89

tree_partition

Partition a large file tree into several file trees of symlinks having equal file counts
Python
2
star
90

go-index-audit

A tool to wait on the Go Proxy to propagate your recent changes before returning
Go
1
star
91

pathhistogram

Generate a histogram of file-sizes within a path. Can also set constraints and write-out the bins.
Python
1
star
92

go-gpsbabel

A wrapper around GPSBabel to allow idiomatic Go to be used to interact with it.
Go
1
star
93

bingrok

A surgical tool for exploring structured binary data
Python
1
star
94

go-exif-extra

Higher-level EXIF and image functionality that works universally across many image formats.
Go
1
star
95

go-http-lifecycle-router

A simple HTTP handler suite that can trigger lifecycle events before and after requests are handled.
Go
1
star
96

PackageBackupClient

Client for the Package Backup package-list backup service.
Python
1
star
97

elasticbeanstalk-test

Go
1
star
98

PypiStats

A jQuery plugin to display a PyPI package's download statistics.
JavaScript
1
star
99

go-gpx-distance

Count the kilometers traveled in GPX data
Go
1
star
100

PythonScheduler

A multithreaded task scheduler that can schedule Python routines to run either at a particular time or at a particular interval.
Python
1
star