问题
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