Skip to main content
 首页 » 编程设计

具有无效语法的 Python while 循环

2025年05月04日15java哥

只是为了在展示代码之前介绍一下我正在从事的项目的背景知识。我目前正在开发一个 Python 脚本,该脚本将在 Raspberry Pi 上运行,以监控地下室污水泵的 float 开关。此代码将根据以下两个标准检查污水泵是否不工作:

  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--^ 

此外,只是对 future 的提示,而不是这样做:

while floatSwitch is True: 

这样做更干净:

while floatSwitch: