我需要每隔10秒从文件中读取一个变量,直到此变量为止
var != "0"
此时我想停止循环。
所以我尝试使用time.sleep
执行while循环来检查文件,但我无法在循环外修改var
,因为它只在while循环中更改:
while var == "0":
file =open("/net/live.txt", "r")
var = file.read()
file.close()
if var == "0":
time.sleep(10) #wait 10 seconds and query again
else:
file2 =open("/net/live2.txt", "w")
file2.write(var)
file2.close()
time.sleep(10)
print var #var is unequal "0" so stop while loop
答案 0 :(得分:0)
如果您使用的是Unix,则可以使用信号模块:
import signal, sys
# your function as signal handler
def handler(signum, frame):
with open("/net/live.txt", "r") as file
var = file.read()
file.close()
if var != '0':
with open("/net/live2.txt", "w") as file2
file2.write(var)
file2.close()
print var
# install handler
signal.signal(signal.SIGALRM, handler)
# emit SIGALRM after 10 secs
signal.setitimer(signal.ITIMER_REAL, 10)
# do other stuff
i = 1
while True:
if i % 100000 == 0:
print i
i += 1
这应该做你期望的。你可以在这里阅读更多有关信号 https://docs.python.org/2/library/signal.html
Windows 用户必须使用Windows自身中的一个现有库,即多媒体库提供计时功能,并且here if found an implementation来自其他开发人员。