" def sleeper"上的语法无效

时间:2016-04-24 09:03:24

标签: python raspbian raspberry-pi3 servo

我正在研究Raspberry Pi上涉及伺服系统的小项目。 我希望伺服系统运行x个时间然后停止。正在尝试我的代码,我目前在"def sleeper"上获得了无效语法,并且不知道为什么。

也是Stackoverflow的新手,我有一些问题缩进代码,我很抱歉!

import RPi.GPIO as GPIO

import time

GPIO.setmode(GPIO.BOARD)

GPIO.setup(7,GPIO.OUT)

try:
                while True:
                        GPIO.output(7,1)
                        time.sleep(0.0015)
                        GPIO.output(7,0)




def sleeper():
    while True:

        num = input('How long to wait: ')

        try:
            num = float(num)
        except ValueError:
            print('Please enter in a number.\n')
            continue

        print('Before: %s' % time.ctime())
        time.sleep(num)
        print('After: %s\n' % time.ctime())


try:
    sleeper()
except KeyboardInterrupt:
    print('\n\nKeyboard exception received. Exiting.')
    exit()

1 个答案:

答案 0 :(得分:1)

那是因为你没有为第一个except对编写任何try ... except块:

这可以按你的意愿工作:

import RPi.GPIO as GPIO

import time

GPIO.setmode(GPIO.BOARD)

GPIO.setup(7,GPIO.OUT)

try:
    while True:
        GPIO.output(7,1)
        time.sleep(0.0015)
        GPIO.output(7,0)
except:
    pass

def sleeper():
    while True:
        num = input('How long to wait: ')
        try:
            num = float(num)
        except ValueError:
            print('Please enter in a number.\n')
            continue

    print('Before: %s' % time.ctime())
    time.sleep(num)
    print('After: %s\n' % time.ctime())

try:
    sleeper()
except KeyboardInterrupt:
    print('\n\nKeyboard exception received. Exiting.')
    exit()

请检查缩进。