From ff9f665c8bbce8aad61a0aead14eb93856ef3dab Mon Sep 17 00:00:00 2001 From: ivanlee Date: Mon, 1 Jul 2019 13:23:03 +0800 Subject: [PATCH] add with as method --- 02_2-led_blink/led_blink.py | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/02_2-led_blink/led_blink.py b/02_2-led_blink/led_blink.py index a0ed422..909d5c0 100644 --- a/02_2-led_blink/led_blink.py +++ b/02_2-led_blink/led_blink.py @@ -20,7 +20,14 @@ GPIO.setmode(GPIO.BOARD) GPIO.setup(LED_PIN, GPIO.OUT) -try: +class control_GPIO: + def __enter__(self): + pass + def __exit__(self,type, value, trace): + print("Exception: KeyboardInterrupt") + GPIO.cleanup() + +with control_GPIO(): while True: print("LED is on") GPIO.output(LED_PIN, GPIO.HIGH) @@ -28,10 +35,4 @@ print("LED is off") GPIO.output(LED_PIN, GPIO.LOW) - time.sleep(1) - -except KeyboardInterrupt: - print("Exception: KeyboardInterrupt") - -finally: - GPIO.cleanup() + time.sleep(1)