简体   繁体   English

在停留在用户输入上时跳出 while 循环

[英]Break out of a while loop while stuck on user input

I have the following code to get user input to do certain tasks.我有以下代码来获取用户输入以执行某些任务。 What I want is to break out of the user prompt when some other task, outside this module, is completed.我想要的是在此模块之外的其他任务完成时跳出用户提示。 So even though the shell is showing 'Enter Command:', I want it to stop waiting for a prompt from the user and continue to the other task.因此,即使外壳显示“输入命令:”,我也希望它停止等待用户的提示并继续执行其他任务。 Is this even possible and if so, how?这甚至可能吗,如果可以,怎么办? Thanks in advance.提前致谢。

    def get_user_input():
        while True:
            info = str(raw_input('Enter Command:'))
            if info == 'exit':
                break
            if info == 'do_something':
                do_something()

Edit: Actually this is already in a thread and the thread closes correctly.编辑:实际上这已经在一个线程中并且该线程正确关闭。 The issue is the screen is stuck on the user prompt even though the user prompt is useless at that point since the thread calling for the input is already closed.问题是屏幕卡在用户提示上,即使此时用户提示无用,因为调用输入的线程已经关闭。 Any suggestions?有什么建议?

Using Signals使用信号

you can use signal module (linux / unix only)您可以使用信号模块(仅限 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')

output when input is 'hello':输入为 'hello' 时的输出:

please insert something here:hello
got hello from user

output when no input for 5 seconds: 5秒无输入时输出:

please insert something here:
no input from user


Using Select使用选择

another option is to use select.select() for non-blocking io operation.另一种选择是使用select.select()进行非阻塞 io 操作。

the get_user_input function tries to read every 0.1 sec the sys.stdin, if there is data to read it reads single byte. get_user_input函数尝试每 0.1 秒读取一次 sys.stdin,如果有数据要读取,它会读取单个字节。 if it encounters a new line it returns the string.如果遇到新行,则返回字符串。

if the timeout passed we exit returning None如果超时,我们退出返回None

the code:编码:

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)

example output for input hello select :输入hello select示例输出:

please insert something:
hello select
input is hello select

example when no input for 5 seconds:例如当 5 秒没有输入时:

please insert something:
no user input

Windows support视窗支持

if you use windows for some reason you can check out this answer about msvcrt module.如果您出于某种原因使用 Windows,您可以查看有关msvcrt模块的答案

basically its the same as select.select for non-blocking io using msvcrt.kbhit() to check if user returned input.基本上它与select.select相同,用于非阻塞 io 使用msvcrt.kbhit()检查用户是否返回输入。

if you need more info please update about your OS.如果您需要更多信息,请更新您的操作系统。

I think you can use this answer to read until a timeout, then check a variable and exit if the variable is set to false.我认为您可以使用此答案读取直到超时,然后检查变量并在变量设置为 false 时退出。 If not then attempt to read again.如果不是,则尝试再次阅读。

https://stackoverflow.com/a/2904057/2066459 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM