Skip to content

Instantly share code, notes, and snippets.

@zerok
Created Nov 27, 2016
Embed
What would you like to do?
A little script for checking when the mtime of a folder changes
from pathlib import Path
from shutil import rmtree
from time import sleep
from contextlib import contextmanager
class Test:
def __init__(self, path):
self.path = path
self.times = self.get_times()
@contextmanager
def test(self, label):
sleep(1)
yield
new_times = self.get_times()
if new_times != self.times:
print("{}: yes".format(label, self.times, new_times))
self.times = new_times
else:
print("{}: no".format(label))
def get_times(self):
stats = self.path.stat()
return stats.st_mtime, stats.st_ctime
def main():
# First create a folder that should be watched (remove it if it already exists)
root = Path('root')
if root.exists():
rmtree('root')
root.mkdir()
t = Test(root)
with t.test("Creating a file changes the times"):
(root / "test.txt").write_text('hello')
with t.test("Creating a folder changes the times"):
(root / "sub").mkdir()
with t.test("Creating a file within the subfolder changes the times"):
(root / "sub" / "test.txt").write_text("lala")
with t.test("Changing attributes of a file changes the times"):
(root / "test.txt").chmod(0o755)
with t.test("Change the content of the file changes the times"):
(root / "test.txt").write_text("something new")
with t.test("Renaming the file changes the times"):
(root / "test.txt").rename(root / "test2.txt")
with t.test("Removing the file changes the times"):
(root / "test2.txt").unlink()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment