我在其他帖子中搜索过,但没有找到解决问题的方法。
我读了一个文件的内容,我需要在20秒后再次查看它是否已被更改。
我使用了threading.Timer,threading.Thread with time.sleep,threading.Event with wait()and Queue - 但每次它都阻塞所有线程,所以文件在等待期间不会被修改,而是在之后。
如何让其他功能修改文件并在20秒后检查更改?
代码:
def function1():
counter = open('textfile.txt', 'r').read()
result = received_msg(counter)
return result
def received_msg(counter):
import time
time.sleep(20)
with open('textfile1.txt', 'r') as c:
newcounter = c.read()
c.close()
if newcounter != counter:
with open('textfile2', 'r') as msgs:
lines = msgs.readlines()
msgs.close()
if lines:
last_line = lines[-1]
return last_line
else:
return "No changes"
这里修改文件的功能:
def inbound():
if request.form.get('token') == TOKEN:
text = request.form.get('text')
counter = open('textfile.txt', 'r').read()
with open('textfile2.txt', 'a+') as msgs:
msgs.write(text+'\n')
msgs.close()
with open('textfile.txt', 'w+') as c2:
newcounter = int(float(counter)) + 1
c2.write(str(newcounter))
c2.close()
return Response(), 200
带线程的版本:
def function1():
import threading, Queue
q = Queue.Queue()
counter = open('textfile.txt', 'r').read()
threading.Timer(20, received_msg, [counter, q]).start()
result = q.get()
return result
def received_msg(counter):
with open('textfile1.txt', 'r') as c:
newcounter = c.read()
c.close()
if newcounter != counter:
with open('textfile2', 'r') as msgs:
lines = msgs.readlines()
msgs.close()
if lines:
last_line = lines[-1]
q.put(last_line)
else:
q.put("No changes")