我有一些代码在 while 循环中记录控制器输入。除了启动/停止功能外,它工作正常。我希望能够通过按一下键随时停止循环。
import inputs
import msvcrt
import keyboard
def record():
'''
Start and stop the input recording with the "\" key
Records controller inputs when they are pressed and depressed and at what time.
'''
print('To start recording, press "q". Press it again to stop')
if msvcrt.getwch() == 'q':
print ("recording started...")
while True:
events = inputs.get_gamepad()
for event in events:
print(event.code)
record()
这是我尝试过做的事情之一。我还尝试使用线程模块将录音功能放入线程中。然而,同样的问题也出现了。当我按下“q”时,它会等待,直到我按下控制器上的另一个按钮。我希望它立即停止循环。
我已将范围缩小到
events = inputs.get_gamepad()
线。看起来循环在这里等待按下按钮,然后它可以返回到开头,从而导致循环正确停止。
import inputs
import msvcrt
import keyboard
recording = True
def interrupt_record():
global recording
recording = False
def record():
'''
Start and stop the input recording with the "\" key
Records controller inputs when they are pressed and depressed and at what time.
'''
print('To start recording, press "q". Press it again to stop')
if msvcrt.getwch() == 'q':
global recording
recording = True
print ("recording started...")
while recording:
events = inputs.get_gamepad()
for event in events:
print(event.code)
keyboard.add_hotkey('q', interrupt_record)
record()
您遇到的问题是因为inputs.get_gamepad() 被阻塞而出现的;也就是说,它在返回之前等待来自控制器的输入事件,并防止循环立即响应按键。
解决方案:使用非阻塞输入检测 为此,您可以重构代码,在 input.get_gamepad() 函数调用上使用非阻塞方法,以便循环可以不断轮询停止条件,而不是无限期地阻塞等待某些控制器输入。
这是一种可能的实现:
import inputs
import keyboard
recording = True # Control flag for the recording loop
def interrupt_record():
"""
Interrupt the recording by setting the global recording flag to False.
"""
global recording
recording = False
print("Recording stopped.")
def record():
"""
Start and stop the input recording with the 'q' key.
Records controller inputs when they are pressed and released, along with timestamps.
"""
print('To start recording, press "q". Press it again to stop.')
# Wait for the 'q' key to start recording
while not keyboard.is_pressed('q'):
pass
global recording
recording = True
print("Recording started... Press 'q' again to stop.")
# Main recording loop
while recording:
try:
# Get gamepad events (non-blocking)
events = inputs.get_gamepad()
for event in events:
print(event.code, event.state)
except inputs.UnpluggedError:
# Handle cases where the controller is not connected
print("Controller disconnected.")
except KeyboardInterrupt:
# Allow for graceful exit with Ctrl+C
break
# Add the hotkey for stopping the recording
keyboard.add_hotkey('q', interrupt_record)
# Start the recording function
record()