[英]Break out of a while loop while stuck on user input
我有以下代码来获取用户输入以执行某些任务。 我想要的是在此模块之外的其他任务完成时跳出用户提示。 因此,即使外壳显示“输入命令:”,我也希望它停止等待用户的提示并继续执行其他任务。 这甚至可能吗,如果可以,怎么办? 提前致谢。
def get_user_input():
while True:
info = str(raw_input('Enter Command:'))
if info == 'exit':
break
if info == 'do_something':
do_something()
编辑:实际上这已经在一个线程中并且该线程正确关闭。 问题是屏幕卡在用户提示上,即使此时用户提示无用,因为调用输入的线程已经关闭。 有什么建议?
您可以使用信号模块(仅限 linux / unix)
import signal
class UserInputTimeoutError(Exception):
pass
def handler(signum, frame):
raise UserInputTimeoutError('no input from user')
# Set the signal handler and a 5-second alarm
signal.signal(signal.SIGALRM, handler)
signal.alarm(5)
try:
# This may hang indefinitely
user_input = raw_input('please insert something here:')
print('got %s from user' % user_input)
# cancel the alarm signal
signal.alarm(0)
except UserInputTimeoutError:
print('\nno input from user')
输入为 'hello' 时的输出:
please insert something here:hello
got hello from user
5秒无输入时输出:
please insert something here:
no input from user
另一种选择是使用select.select()
进行非阻塞 io 操作。
get_user_input
函数尝试每 0.1 秒读取一次 sys.stdin,如果有数据要读取,它会读取单个字节。 如果遇到新行,则返回字符串。
如果超时,我们退出返回None
编码:
import select
import sys
import time
def get_user_input(msg, timeout=5):
print(msg)
user_input = []
stime = time.time()
while time.time() - stime <= timeout:
readables, _, _ = select.select([sys.stdin], [], [], 0.1)
if not readables:
continue
chr = readables[0].read(1)
if chr == '\n':
return ''.join(user_input)
user_input.append(chr)
user_input = get_user_input('please insert something:')
if user_input is None:
print('no user input')
else:
print('input is %s' % user_input)
输入hello select
示例输出:
please insert something:
hello select
input is hello select
例如当 5 秒没有输入时:
please insert something:
no user input
如果您出于某种原因使用 Windows,您可以查看有关msvcrt
模块的答案。
基本上它与select.select
相同,用于非阻塞 io 使用msvcrt.kbhit()
检查用户是否返回输入。
如果您需要更多信息,请更新您的操作系统。
我认为您可以使用此答案读取直到超时,然后检查变量并在变量设置为 false 时退出。 如果不是,则尝试再次阅读。
https://stackoverflow.com/a/2904057/2066459
import sys, select
print "Answer me!"
while var:
i, o, e = select.select( [sys.stdin], [], [], 10 )
if (i):
print "You said", sys.stdin.readline().strip()
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.