直到在python3中检测到输入之前,如何做某事? [英] How to do something till an input is detected in python3?

查看:70
本文介绍了直到在python3中检测到输入之前,如何做某事?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行一段代码,直到用户输入输入(检测到随机按键)为止,如何在Python 3.x中做到这一点?

I want to execute a piece of code till the user enters an input(detects a random keypress), how do I do that in Python 3.x?

这是伪代码:

while input == False:
    print(x)

推荐答案

您可以这样做:

try:
    while True:
        print("Running")
except KeyboardInterrupt:
    print("User pressed CTRL+c. Program terminated.")

用户只需要按Control + c.

The user just need to press Control+c.

Python提供了内置异常 KeyboardInterrupt 来处理此异常

Python provide the built-in exception KeyboardInterrupt to handle this.

要使用 pynput

import threading
from pynput.keyboard import Key, Listener

class MyClass():
    def __init__(self) -> None:
        self.user_press = False

    def RandomPress(self, key):
        self.user_press = True

    def MainProgram(self):
        while self.user_press == False:
            print("Running")
        print("Key pressed, program stop.")

    def Run(self):
        t1 = threading.Thread(target=self.MainProgram)
        t1.start()

        # Collect events until released
        with Listener(on_press=self.RandomPress) as listener:
            listener.join()

MyClass().Run()

这篇关于直到在python3中检测到输入之前,如何做某事?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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