forked from Norore/jebif
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonitor.py
More file actions
86 lines (69 loc) · 1.87 KB
/
Copy pathmonitor.py
File metadata and controls
86 lines (69 loc) · 1.87 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import os
import sys
import time
import signal
import threading
import atexit
from queue import Queue
_interval = 1.0
_times = {}
_files = []
_running = False
_queue = Queue()
_lock = threading.Lock()
def _restart(path):
_queue.put(True)
prefix = 'monitor (pid=%d):' % os.getpid()
# print('%s Change detected to \'%s\'.' % (prefix, path), file=sys.stderr)
# print('%s Triggering process restart.' % prefix, file=sys.stderr)
os.kill(os.getpid(), signal.SIGINT)
def _modified(path):
try:
# Check for when file last modified.
mtime = os.stat(path).st_mtime
if path not in _times:
_times[path] = mtime
# Force restart when modification time has changed, even
# if time now older, as that could indicate older file
# has been restored.
if mtime != _times[path]:
return True
except:
pass
return False
def _monitor():
while 1:
# Check modification times on files which have
# specifically been registered for monitoring.
for path in _files:
if _modified(path):
return _restart(path)
# Go to sleep for specified interval.
try:
return _queue.get(timeout=_interval)
except:
pass
_thread = threading.Thread(target=_monitor)
_thread.setDaemon(True)
def _exiting():
try:
_queue.put_nowait(True)
except:
pass
# _thread.join()
atexit.register(_exiting)
def track(path):
print(path)
if not path in _files:
_files.append(path)
def start(interval=1.0):
global _interval
_interval = interval
global _running
_lock.acquire()
if not _running:
prefix = 'monitor (pid=%d):' % os.getpid()
# print('%s Starting change monitor.' % prefix, file=sys.stderr)
_running = True
_thread.start()
_lock.release()