我想执行一段代码,直到用户输入(检测到随机按键(,在Python 3.x中如何做到这一点?
这是伪代码:
while input == False:
print(x)
你可以这样做:
try:
while True:
print("Running")
except KeyboardInterrupt:
print("User pressed CTRL+c. Program terminated.")
用户只需按Control+c即可。
Python提供了内置的异常KeyboardInterrupt来处理此问题。
要使用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()
如果你想与用户互动,你可以按照以下方式进行:
flag = input("please enter yes or no?")
if flag == "no":
print(x)