在 python3 中检测到输入之前如何做某事?
How to do something till an input is detected in python3?
我想执行一段代码直到用户输入(检测到 随机 按键),我如何在 Python [=18 中执行此操作=]?
这是伪代码:
while input == False:
print(x)
你可以这样做:
try:
while True:
print("Running")
except KeyboardInterrupt:
print("User pressed CTRL+c. Program terminated.")
用户只需按 Control+c。
Python 提供 built-in 异常 KeyboardInterrupt 来处理这个问题。
用 pynput
随机 key-press
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)
我想执行一段代码直到用户输入(检测到 随机 按键),我如何在 Python [=18 中执行此操作=]?
这是伪代码:
while input == False:
print(x)
你可以这样做:
try:
while True:
print("Running")
except KeyboardInterrupt:
print("User pressed CTRL+c. Program terminated.")
用户只需按 Control+c。
Python 提供 built-in 异常 KeyboardInterrupt 来处理这个问题。
用 pynput
随机 key-pressimport 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)