python监听文件是否发生改变。
环境
-
Python3.9
-
Pathlib(自带)
大致逻辑
- 获取到所有的项目文件
- 获取到所有文件的最后修改时间,并记录下来
- 死循环,对比当前文件修改的时间和上一次修改的时间是否一样,如果不一样就表示被修改过
注意事项
在Linux和Mac系统里面,当我们在修改文件的时候,会生成一个临时文件。
代码实现
"""
监听文件是否发生变化
"""
import sys
from functools import lru_cache
from os import listdir, getcwd
from os.path import isdir, join
from pathlib import PosixPath
from time import sleep
class WatchFile(object):
__doc__ = """
监听文件是否发生变化
1. 获取指定模块当所有文件
2. 设置PosixPath对象,然后获取到最后访问时间
3. 根据修改时间修改,然后查看文件是否被修改,如果被修改就发送信号
4. 记录文件的上一次修改时间,然后根据这次进行对比
"""
exclude_files = ['.idea', '.venv', '.git']
change_log = {} # key文件名 value修改时间
global_time = 1 # 每次循环完所有文件,等待的时间
@lru_cache(maxsize=1)
def get_file_path(self, path):
"""
获取当前模块的所有文件
:return:
"""
for file in listdir(path):
if isdir(join(path, file)):
if file in self.exclude_files:
continue
yield from self.get_file_path(join(path, file))
else:
yield join(path, file)
def watch_file(self, path):
"""
:param path:
:return:
"""
while True:
for file_path in self.get_file_path(path):
"""
因为当我们修改后,会生成一个临时文件修:修改文件~,要对他进行过滤,
"""
posix_path = PosixPath(file_path)
if not posix_path.exists():
continue
st_mtime = posix_path.stat().st_mtime
change_time = self.change_log.get(file_path, None)
if change_time and change_time != st_mtime:
print('hello world')
# 文件修改过
print("%s 文件被修改了 %s" % (file_path, change_time))
self.change_log[file_path] = st_mtime
elif not change_time:
self.change_log[file_path] = st_mtime
if __name__ == '__main__':
watch_file = WatchFile()
watch_file.watch_file(getcwd())