Skip to main content
 首页 » 编程设计

python之如何通过检测按键来打破 Python 中的循环

2025年05月04日9mfrbuaa

from subprocess import call 
try: 
    while True: 
        call (["raspivid -n -b 2666666.67 -t 5000 -o test.mp4"],shell=True) 
        call (["raspivid -n -b 2666666.67 -t 5000 -o test1.mp4"],shell=True) 
except KeyboardInterrupt: 
    pass 

我计划在按下任何 按钮时让它中断循环。然而,我尝试了很多方法来破解,但没有一个奏效。

请您参考如下方法:

您希望您的代码更像这样:

from subprocess import call 
 
while True: 
    try: 
        call(["raspivid -n -b 2666666.67 -t 5000 -o test.mp4"], shell=True) 
        call(["raspivid -n -b 2666666.67 -t 5000 -o test1.mp4"], shell=True) 
    except KeyboardInterrupt: 
        break  # The answer was in the question! 

你 break一个完全符合您预期的循环。