python threading模块监控文件是否被修改

发布时间:2019-11-07编辑:脚本学堂
python脚本中借助threading模块监控文件变化情况,python监控文件是否被修改的实现代码,一起学习下。

例子,threading与python os模块,以及python time模块的入门实例,监控文件变化。

代码:
 

复制代码 代码示例:

#!/usr/bin/env python
#
import threading
import os
import time

def MyThread():
lastStat = os.stat(inFile)
lastModifyTime = lastStat.st_mtime
while True:
newStat = os.stat(inFile)
modifyTime = newStat.st_mtime
if lastModifyTime != modifyTime :
docSize = newStat.st_size
lastModifyTime = modifyTime
print "document was modified last 3 seconds, and now its size is %s" % (docSize)
else:
print "document was not modified last 3 seconds!"
time.sleep(3)

if __name__ == '__main__':
global inFile
inFile = 'a.txt' # test document
refreshThread = threading.Thread(target=MyThread)
refreshThread.setDaemon(True)
refreshThread.start() 
print "------start------ %s" % (time.ctime())
time.sleep(30)
print "------end------ %s" % (time.ctime())