-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathwatcher.py
More file actions
105 lines (70 loc) · 2.24 KB
/
watcher.py
File metadata and controls
105 lines (70 loc) · 2.24 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
from os import path
from subprocess import PIPE, TimeoutExpired, run
from sys import argv
from time import perf_counter, sleep
TIME_FOR_WAIT = 3 # Time in seconds for waiting
def getFile() -> str:
"""Get file name from command line"""
if argv[1::]:
return argv[1]
else:
print(f"usage: python {argv[0]} <filename>")
quit()
def getmtime(filename: str) -> float:
"""Get last modified time of the given file"""
return path.getmtime(filename)
def timer(func):
"""Timer decorator for calculating time taken by a function"""
def wrapper(*args, **kwargs) -> None:
start = perf_counter()
func(*args, **kwargs)
print(f"\nThis Process Takes {(perf_counter() - start):.2f} Seconds")
return wrapper
@timer
def runFile(filename: str) -> None:
"""Run file"""
print("Running File")
try:
process = run(
["python3", filename], text=True, encoding="utf-8", stderr=PIPE, timeout=30
)
if process.returncode:
print(f"Error: {process.stderr}")
except KeyboardInterrupt:
print()
except TimeoutExpired:
print("Execution timed out after 30 seconds")
except Exception:
print("Something went wrong!")
print("\nWatching ..... ", end="")
def watcher(filename: str) -> None:
"""Watch file for changes and run it when changed is detected"""
lastModified = getmtime(filename)
print("Watching ..... ", end="", flush=True)
while True:
lastmt = getmtime(filename)
if lastModified != lastmt:
sleep(TIME_FOR_WAIT)
if lastmt != getmtime(filename):
continue
runFile(filename) # Running File
try:
lastModified = getmtime(filename)
except FileNotFoundError:
continue
else:
try:
sleep(0.5)
except KeyboardInterrupt:
print()
quit()
def main():
filename = getFile()
if not path.exists(filename):
print("File Not Found!")
elif filename.split(".")[-1] == "py":
watcher(filename)
else:
print("Only Python File Supported!")
if __name__ == "__main__":
main()