【问题标题】:How can I make a python script stop itself after 10 seconds?如何让 python 脚本在 10 秒后自行停止?
【发布时间】:2017-03-18 05:58:04
【问题描述】:

我正在开发自己的一个项目,该项目涉及树莓派上的伺服系统。我在执行代码时让它们旋转,但我更愿意让 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()

【问题讨论】:

  • 检查是否过了10秒,然后退出循环。

标签: python linux time raspberry-pi servo


【解决方案1】:

尝试以下方法:

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()

【讨论】:

  • 像魅力一样工作!非常感谢。
【解决方案2】:

试试这个

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    • 2022-06-15
    • 2015-09-22
    • 2013-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多