Python';除';语法错误
我正在写一个在我的Raspberry Pi上运行的程序,我似乎无法克服这个pesty语法错误。这是我的密码:Python';除';语法错误,python,Python,我正在写一个在我的Raspberry 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.O
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
我似乎找不到问题所在。有人能帮忙吗?您应该将您的函数放在
try
块中:
# Main program loop
try:
while True:
print RCtime(4) # Measure timing using GPIO4
except KeyboardInterrupt:
GPIO.cleanup()
我认为这会起作用。因为这个术语叫做try…除了语句之外,你必须有一个
try
关键字。环绕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 except
语句中匹配的try
部分。try-except返回相同的错误@DYZ请更新代码,然后包括新的错误消息。到目前为止,您向我们展示的内容肯定是不正确的。对于GPIO清理,使用try…finally
是一个好习惯。这样,如果程序正常退出(在此程序中不可能,但在其他程序中可能),清理仍会进行。此外,您不会丢失错误,这在调试时非常有帮助…通常我同意您希望在异常捕获范围内保留尽可能少的错误-但在这种情况下,我们总是希望清理运行。因此,用这种方式包装整个程序不是一个坏主意。