我想运行一个 Python 脚本,该脚本在指定的时间段(例如一周)内寻找与之交互的人。如果有人与它互动,它就会继续寻找互动的另一个循环。如果有人不与之交互,则它开始执行某些操作。
我已经使用模块信号(以及 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()
你可以简单地写:
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)