Python while循环语法无效

时间:2013-09-29 19:29:18

标签: python while-loop

在我展示代码之前,先介绍一下我正在研究的项目。我目前正在开发一个Python脚本,它将在Raspberry Pi上运行,以便从我地下室的污水泵中监控浮动开关。此代码将检查污水泵是否不符合以下两个标准:

  1. 如果开关打开超过三分钟
  2. 如果开关在三分钟内开启和关闭超过10次
  3. 我没有完成剩下的代码,但这就是我所拥有的:

    import time
    
    import RPi.GPIO as GPIO
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(17, GPIO.IN)
    floatSwitch = GPIO.input(17)
    
    import smtplib
    
    running = True
    log = open("sumpPumpLog.txt", "r+")
    startTime = time.time()
    
    
    def elapsedTime():
        """This function checks how much time
        has elapsed since the timer has started"""
        endtime = time.time()
        elapsed = endtime - starttime
        return elapsed
    
    
    def sendEmail(*msg):
        """This function sends an email to selected recipients with a custom
        message as well as the log file attached."""
        #enter the code that sends an email to the family with the log attached
    
        fromaddr = 'from@email.com'
        toaddrs = [to@email.com']
        msg = """Please see the Pi and the data log file for more details."""
    
        # Credentials (if needed)
        username = 'my_username'
        password = 'my_password'
    
        msg.attached()
    
        # The actual mail send
        server = smtplib.SMTP('smtp.gmail.com:587')
        server.starttls()
        server.login(username, password)
        server.sendmail(fromaddr, toaddrs, msg)
        server.quit()
    
    
    if running is True:
        if floatSwitch is True:
            #Write the time and what happened to the file
            log.write(str(time.time() + "Float switch turned on")
            #Wait until switch is turned off
    
            while floatSwitch is True:
                startTime = time.time()
                if floatSwitch is False:
                    log.write(str(now) + "Float switch turned off")
                    break
            #if elapsedTime > 3 min (in the form of 180 seconds)
            elif elapsedTime() > 180:
                log.write(str(now) + "Sump Pump has been deemed broaken")
                sendEmail("The sump pump is now broken.")
    
    else:
        log.write(str(time.time() + "The sctipt has stopped.")
        sendEmail("The script has been stopped.")
    

    我的问题是在第52行说出

    while floatSwitch is True:
    

    代码中有错误,所有内容都是“语法无效” 我是Python的新手,这是我的第一个真正的项目。我不熟悉很多语法,所以这可能是一个非常基本的错误。任何人都可以帮我修复这个语句的语法,以便我可以让我的代码工作。我知道在没有剩下的代码的情况下还有很多其他错误,但我计划在找到它们时解决这些错误。我四处寻找,但我找不到像这样的另一个例子。非常感谢任何和所有的帮助!

2 个答案:

答案 0 :(得分:4)

实际上,问题在于上面的行 while循环。你缺少一个括号:

log.write(str(time.time() + "Float switch turned on"))
                                               here--^

此外,只是未来的提示,而不是这样做:

while floatSwitch is True:

这样做更干净:

while floatSwitch:

答案 1 :(得分:2)

上一行中有一个不平衡的括号:

log.write(str(time.time() + "Float switch turned on"))  # Last parenthesis is missing

而且在sendEmail()方法中,你有一个缺失的开场语:

toaddrs = [to@email.com']  # Opening quote missing