0

我正在做一个涉及伺服系统的小项目Raspberry Pi。我希望伺服系统运行 x 时间然后停止。正在尝试我的代码,目前正在使用 Invalid syntax"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()
4

1 回答 1

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()

请检查缩进。

于 2016-04-24T09:10:40.760 回答