aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/inotify.py
blob: 84b24e9e91d216a87b3251f65e8e2d1e6143881d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# -*- python -*-
'''
xpybar – xmobar replacement written in python
Copyright © 2014, 2015, 2016  Mattias Andrée (maandree@member.fsf.org)

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 3 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, see <http://www.gnu.org/licenses/>.
'''

import os

from util import *

from plugins.linereader import LineReader



class Inotify:
    '''
    File access monitor
    '''
    
    def __init__(self, callback, *arguments, events = None):
        '''
        Constructor
        
        @param  callback:(str)→void  Function that will be called everytime a line is read from
                                     `inotifywait`'s standard output, the parameter will be that line,
                                     note that this will not be asynchronously, you may want to specify
                                     something like `lambda : async(fun)` for that, and use semaphores
                                     in `fun`.
        @param  arguments:*str       The files and directories you want to watch and any addition
                                     argument you want to pass to `inotifywait`
        @param  event:itr<str>?      Event you want reported, see "EVENTS" under `inotifywait`'s man page
        '''
        command = ['inotifywait', '-m']
        if events is not None:
            if isinstance(events, str):
                events = [events]
            for event in events:
                command.append('-e')
                command.append(event)
        command += list(arguments)
        if 'PATH' in os.environ:
            path = os.environ['PATH'].split('.')
            for p in path:
                p += '/pdeath'
                if os.access(p, os.X_OK, effective_ids = True):
                    command = [p, 'HUP'] + command
                    break
        def start():
            with LineReader(spawn(*command)) as reader:
                while True:
                    callback(reader.next())
        async(start)