How to do something till an input is detected in python3?

血红的双手。 提交于 2021-01-27 22:00:26

问题


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?

Here is the pseudo-code:

while input == False:
    print(x)

回答1:


You can do it like this:

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

The user just need to press Control+c.

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

To do it with any random key-press with 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()



回答2:


If you want to interact with users, you may follow the below way:

flag = input("please enter yes or no?")
if flag == "no":
    print(x)


来源:https://stackoverflow.com/questions/63754139/how-to-do-something-till-an-input-is-detected-in-python3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!