Python - 无限循环,中断用户输入 [英] Python - Infinite while loop, break on user input

查看:42
本文介绍了Python - 无限循环,中断用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个无限的 while 循环,我想在用户按下某个键时跳出该循环.通常我使用 raw_input 来获取用户的响应;但是,我需要 raw_input 不等待响应.我想要这样的东西:

I have an infinite while loop that I want to break out of when the user presses a key. Usually I use raw_input to get the user's response; however, I need raw_input to not wait for the response. I want something like this:

print 'Press enter to continue.'
while True:
    # Do stuff
    #
    # User pressed enter, break out of loop

这应该是一个简单的,但我似乎无法弄清楚.我倾向于使用线程的解决方案,但我宁愿不必这样做.我怎样才能做到这一点?

This should be a simple, but I can't seem to figure it out. I'm leaning towards a solution using threading, but I would rather not have to do that. How can I accomplish this?

推荐答案

我认为你可以用 msvcrt 做得更好:

I think you can do better with msvcrt:

import msvcrt, time
i = 0
while True:
    i = i + 1
    if msvcrt.kbhit():
        if msvcrt.getwche() == '\r':
            break
    time.sleep(0.1)
print(i)

遗憾的是,仍然是特定于 Windows 的.

Sadly, still windows-specific.

这篇关于Python - 无限循环,中断用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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