TGFoxy TGFoxy - 28 days ago 13
Linux Question

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

I am working on a project of my own that involves servos on a raspberry pi. I have them spinning when I execute the code but I'd prefer to have the python script kill itself after 10 seconds, rather then having to hit CTRL + C all the time. Is there a way to do this with this particular code?

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

Answer

Try something like the following:

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