Python'除'语法错误

时间:2017-04-19 02:26:49

标签: python

我正在编写一个程序在我的Raspberry Pi上运行,我似乎无法克服这个简单的语法错误。这是我的代码:

import RPi.GPIO as GPIO, time

GPIO.setmode(GPIO.BCM)

GPIO.setup(14,GPIO.OUT)

GPIO.output(14,GPIO.HIGH)

def RCtime (PiPin):
  measurement = 0
  # Discharge capacitor
  GPIO.setup(PiPin, GPIO.OUT)
  GPIO.output(PiPin, GPIO.LOW)
  time.sleep(0.1)

  GPIO.setup(PiPin, GPIO.IN)
  # Count loops until voltage across
  # capacitor reads high on GPIO
  while (GPIO.input(PiPin) == GPIO.LOW):
    measurement += 1

  return measurement

# Main program loop
while True:
  print RCtime(4) # Measure timing using GPIO4

except KeyboardInterrupt:
  GPIO.cleanup()

返回以下错误:

File "measure.py", line 28
    except KeyboardInterrupt:
         ^
SyntaxError: invalid syntax

我似乎无法找到问题所在。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

您应该将您的功能放在try区块中:

# Main program loop
try:
    while True:
        print RCtime(4) # Measure timing using GPIO4
except KeyboardInterrupt:
    GPIO.cleanup()

我认为这会奏效。

答案 1 :(得分:0)

由于该术语称为try ... except语句,因此您必须拥有try个关键字。包裹尝试...除了你想要错误处理的行周围。注意:你应该尽可能少地包装:

while True:
  try:
    print RCtime(4) # Measure timing using GPIO4
  except KeyboardInterrupt:
    break # break the while loop
  finally:
    GPIO.cleanup() # GPIO clean up

编辑:正如建议的那样,无论是否存在异常,都应该运行GPIO清理,你应该将清理操作放在finally子句中。