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

查看:101
本文介绍了通过按回车而不阻塞来退出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"?

最初,如果我键入了一堆字符然后按回车键,它并没有停止循环.我将不得不再次按Enter键. if组件和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.

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

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