Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 按enter键退出while循环而不阻塞。如何改进此方法?_Python_Loops_Input_Exit_Enter - Fatal编程技术网

Python 按enter键退出while循环而不阻塞。如何改进此方法?

Python 按enter键退出while循环而不阻塞。如何改进此方法?,python,loops,input,exit,enter,Python,Loops,Input,Exit,Enter,因此,我一直在阅读一些关于如何通过用户按enter键退出while循环的内容,我得出了以下结论: 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

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

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”看起来很混乱。它们可以合并成一个吗?使用“开关”的更好选择

最初,如果我输入一堆字符,然后按enter键,它不会停止循环。我必须再次按回车键。if not和else组件旨在对其进行设置,使其在第一次按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

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

为什么不去掉
if
,因为这两种方式都是一样的?另外,
虽然True
break
比flag更整洁,但这在Windows上实际起作用吗?文档说select.select只支持Windows上的套接字:@Weeble我想这应该适用于Windows?我个人在Ubuntu上编程,搞定了。非常感谢。事实上,事后来看,我意识到你甚至不需要
如果行或不行
。。。这总是正确的。但是您确实需要原始输入()调用,因为如果用户输入除Enter之外的任何内容,然后按Enter键,则会抛出一个名称错误。如果我有足够的rep,我会彻底放弃您的解决方案。我希望其他人能从中受益!这是一个很好的答案。以下是(我相信)原始来源,其中包含关于非阻塞标准输入的更多信息: