Home > Mobile >  How do I run automatically run a command once my program ends?
How do I run automatically run a command once my program ends?

Time:08-20

I am currently coding on python3 and have a while True loop where it will run indefinitely so I have to force stop it for it to end. For further details, I am creating a system that automatically detects the humidity in a box, and starts a fan, once it reaches a high enough humidity. When I force stop my program, I would like it to run a command, specifically GPIO.output(21, GPIO.LOW), this will cause the fan to turn off. Any ideas? (I'm currently using a raspberry pi 3 to code this all on)

CodePudding user response:

Here's an example of you can detect SIGINT (Ctrl-C):

from time import sleep
from signal import signal, SIGINT, SIG_DFL

INTERRUPTED = False

def handler(signum, _):
    global INTERRUPTED
    signal(signum, SIG_DFL)
    INTERRUPTED = True

signal(SIGINT, handler)

while not INTERRUPTED:
    sleep(1)

print('Interrupted')

So here we have a potentially infinite loop but having set a handler for SIGINT we can break out of the loop upon receipt of that signal and run some cleanup code or whatever else may be necessary

CodePudding user response:

Capture an input to break out of your loop instead of manually closing the program, then put GPIO.output(21, GPIO.LOW) after the loop. Or if you are set on manually ending the program perhaps manually start a separate program right after that only runs that single command?

  • Related