简体   繁体   中英

Why is this usage of "except" a syntax error in Python 3?

I am trying to write a simple program which will turn lights on and off based on the time of day, in Python 3.

I keep on getting a syntax error when try and use except KeyboardInterrupt: in a while loop. This is the error:

except KeyboardInterrupt:
^
SyntaxError: invalid syntax

As I have doubled checked the syntax with online documentation I am at a loss as to what I am doing wrong and I guess I am missing some piece of understanding here.

Here is the full code for reference:

#!/usr/bin/python  

import time
import datetime

TimeStart = datetime.time(17, 0, 0)
TimeEnd = datetime.time(18, 30, 0)

def onoff():
    while True:
        if TimeEnd > datetime.datetime.now().time() and TimeStart < datetime.datetime.now().time():
            print("Pin 18  High")
        else:
            print("Pin 18  Low")
        except KeyboardInterrupt:
            pass
            print("Error..... Quiting.....")
            raise
            sys.exit()

time.sleep(30)   
onoff()

You cannot use the except statement outside of a try: ... except: ... code block.

https://docs.python.org/3/tutorial/errors.html#handling-exceptions

So you would rephrase your code as

while True:
    try:
        if TimeEnd > datetime.datetime.now().time() and TimeStart < datetime.datetime.now().time() :
            print ("Pin 18  High")
        else:
            print ("Pin 18  Low")
    except KeyboardInterrupt:
        pass
        print("Error..... Quiting.....")
        raise
        sys.exit()

which I haven't tried but essentially

  • wraps the if statement with a try clause, and
  • any KeyboardInterrupt would be captured by the except statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM