我希望运行一个Python脚本,寻找某人在指定的时间段内(比如一周)与之交互。如果有人与之交互,它将继续寻找互动的另一个循环。如果某人没有与之互动,则会开始执行某些操作。
我已经使用模块signal启动了这样的脚本(并且示例超时为20秒),但是超时似乎没有起作用;该脚本立即启动到非交互操作。出了什么问题?有没有更好的方法解决这个问题?
#!/usr/bin/env python
import propyte
import signal
import time
def main():
response = "yes"
while response == "yes":
response = get_input_nonblocking(
prompt = "ohai?",
timeout = 20 #604800 s (1 week)
)
print("start non-response procedures")
# do things
def alarm_handler(signum, frame):
raise Exception
def get_input_nonblocking(
prompt = "",
timeout = 20, # seconds
message_timeout = "prompt timeout"
):
signal.signal(signal.SIGALRM, alarm_handler)
signal.alarm(timeout)
try:
response = propyte.get_input(prompt)
signal.alarm(0)
return response
except Exception:
print(message_timeout)
signal.signal(signal.SIGALRM, signal.SIG_IGN)
return ""
if __name__ == '__main__':
main()
答案 0 :(得分:2)
您可以简单地写一下:
import signal
TIMEOUT = 20 * 60 # secs to wait for interaction
def interrupted(signum, frame):
"called when read times out"
print('Exiting')
signal.signal(signal.SIGALRM, interrupted)
def i_input():
try:
print('You have 20 minutes to interact or this script will cease to execute')
foo = input()
return foo
except:
# timeout
return
# set alarm
signal.alarm(TIMEOUT)
inp = i_input()
# disable the alarm if not wanted any longer
# signal.alarm(0)