如何让 python 脚本在 10 秒后自行停止?

How can I make a python script stop itself after 10 seconds?

我正在做一个我自己的项目,涉及 raspberry pi 上的伺服系统。我在执行代码时让它们旋转,但我更希望 python 脚本在 10 秒后自行终止,而不是一直按 CTRL + C。有没有办法用这个特定的代码来做到这一点?

import RPi.GPIO as GPIO

import time

GPIO.setmode(GPIO.BOARD)

GPIO.setup(7,GPIO.OUT)

try:
                while True:
                        GPIO.output(7,1)
                        time.sleep(0.0015)
                        GPIO.output(7,0)

                        time.sleep(0.01)

except KeyboardInterrupt:
       print"Stopping Auto-Feeder"
       GPIO.cleanup()

尝试如下操作:

import RPi.GPIO as GPIO
import time


stop_time = time.time() + 10

GPIO.setmode(GPIO.BOARD)
GPIO.setup(7,GPIO.OUT)

try:
    while time.time() < stop_time:
            GPIO.output(7,1)
            time.sleep(0.0015)
            GPIO.output(7,0)

            time.sleep(0.01)

except KeyboardInterrupt:
    pass

print"Stopping Auto-Feeder"
GPIO.cleanup()

试试这个

wait = 10
while wait > 0:
    print(wait)
    time.sleep(1)
    wait = wait - 1```