繁体   English   中英

Python while循环使用无效语法

[英]Python while loop with invalid syntax

只是为了在展示代码之前为我正在从事的项目提供一些背景知识。 我目前正在开发一个Python脚本,该脚本将在Raspberry Pi上运行,以监视来自地下室污水泵的浮球开关。 此代码将根据以下两个条件检查污水泵是否不起作用:

  1. 如果开关超过三分钟
  2. 如果三分钟内开关打开和关闭超过10次

我还没有用完其余的代码,但是这里是我所拥有的:

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还是很陌生,这是我第一个使用它的真实项目。 我不熟悉很多语法,因此这可能是一个非常基本的错误。 谁能帮助我修复此语句的语法,以便使我的代码正常工作。 我知道在没有其余代码的情况下还有许多其他错误,但是我计划在发现这些错误时加以解决。 我到处搜索,但是找不到其他这样的示例。 任何帮助都非常感谢!

实际上,您的问题出在while循环上方 您缺少括号:

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

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

while floatSwitch is True:

这样做比较干净:

while floatSwitch:

上一行的括号不平衡:

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

而且在sendEmail()方法中,您还缺少开头的引号:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM