按 Enter 退出 while 循环而不阻塞.我该如何改进这种方法? [英] Exiting while loop by pressing enter without blocking. How can I improve this method?

查看:22
本文介绍了按 Enter 退出 while 循环而不阻塞.我该如何改进这种方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我一直在阅读有关如何通过用户按下 Enter 键退出 while 循环的一些内容,并得出以下结论:

So I've been doing a little bit of reading up on how to exit a while loop by the user pressing the enter key and I've come up with the following:

import sys, select, os

switch = 1
i = 1
while switch == 1:
    os.system('cls' if os.name == 'nt' else 'clear')
    print "I'm doing stuff. Press Enter to stop me!"
    print i
    while sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
        line = raw_input()
        if not line:
            print "Finished! =]"
            switch = 0
        else:
            print "Finished! =]"
            switch = 0
    i = i+1

有没有办法整理一下?特别是if not line"和下面的else"看起来很乱.它们可以合二为一吗?使用开关"的更好替代方法?

Is there a way to tidy this up? In particular the "if not line" and the following "else" look messy. Can they be combined into one? A better alternative to using "switch"?

最初,如果我输入一堆字符然后按回车键,它并没有停止循环.我将不得不再次按回车键.if not 和 else 组件旨在将其设置为在第一次按下 Enter 时退出.

Initially if I typed a bunch of characters and then hit enter it didn't stop the loop. I would have to press enter again. The if not and else components are intended to set it up such that it would exit on the first press of enter.

推荐答案

这对我有用:

import sys, select, os

i = 0
while True:
    os.system('cls' if os.name == 'nt' else 'clear')
    print "I'm doing stuff. Press Enter to stop me!"
    print i
    if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
        line = raw_input()
        break
    i += 1

您只需要检查一次输入的标准输入(因为第一个输入将终止循环).如果条件行/非行对您有结果,您可以将它们组合成一个 if 语句.然后,只使用一个 while 语句,您现在可以使用 break 而不是设置标志.

You only need to check for the stdin being input once (since the first input will terminate the loop). If the conditions line/not line have result for you, you can combine them to one if statement. Then, with only one while statement being used, you can now use break instead of setting a flag.

这篇关于按 Enter 退出 while 循环而不阻塞.我该如何改进这种方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆