Python 获取输入时停止

发布于 2024-09-27 12:40:11 字数 53 浏览 1 评论 0原文

如何在 Python 中运行循环并对其进行编码以在用户按下按钮(而不是 ctr+c)时停止?

How can I run a loop in Python and code it to stop when the user press a button (not ctr+c)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

永不分离 2024-10-04 12:40:11

我遇到了类似的问题,找到了这段代码摘录对我有帮助。

#!/usr/bin/env python
import curses

def main(win):
win.nodelay(True) # make getkey() not wait
x = 0
while True:
    #just to show that the loop runs, print a counter
    win.clear()
    win.addstr(0,0,str(x))
    x += 1

    try:
        key = win.getkey()
    except: # in no delay mode getkey raise and exeption if no key is press 
        key = None
    if key == " ": # of we got a space then break
        break

#a wrapper to create a window, and clean up at the end
curses.wrapper(main)

当然,问题是使用诅咒会阻止许多其他事情(例如打印)工作,但有一些方法可以解决这个问题。

I had a similar problem, found this code excerpt that helped me.

#!/usr/bin/env python
import curses

def main(win):
win.nodelay(True) # make getkey() not wait
x = 0
while True:
    #just to show that the loop runs, print a counter
    win.clear()
    win.addstr(0,0,str(x))
    x += 1

    try:
        key = win.getkey()
    except: # in no delay mode getkey raise and exeption if no key is press 
        key = None
    if key == " ": # of we got a space then break
        break

#a wrapper to create a window, and clean up at the end
curses.wrapper(main)

The problem of course is that using curses will prevent a lot of other things (like print) from working but there are ways around that.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文