Python“except”语法

2024-06-17 10:36:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个程序运行在我的树莓Pi上,我似乎无法通过这个pesty语法错误。这是我的代码:

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

我好像找不到问题。有人能帮忙吗?


Tags: 程序运行outputgpiotimesetuppiout树莓
2条回答

由于该术语称为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子句中。

您应该将函数放在try块中:

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

我想这能行。

相关问题 更多 >