0

我正在编写一个 Python 程序,我想同时运行两个 while 循环。我对 Python 很陌生,所以这可能是一个基本的错误/误解。该项目使用 Raspberry Pi 监控污水泵以确保其正常工作,如果没有,则向指定的收件人发送电子邮件。一个循环将与用户交互,并通过 SSH 实时响应发送给它的命令。

while running is True:

    user_input = raw_input("What would you like to do? \n").lower()

    if user_input == "tell me a story":
        story()
    elif user_input == "what is your name":
        print "Lancelot"
    elif user_input == "what is your quest":
        print "To seek the Holy Grail"
    elif user_input == "what is your favorite color":
        print "Blue"
    elif user_input == "status":
        if floatSwitch == True:
            print "The switch is up"
        else:
            print "The switch is down"
    elif user_input == "history":
        print log.readline(-2)
        print log.readline(-1) + "\n"
    elif user_input == "exit" or "stop":
        break
    else:
        print "I do not recognize that command. Please try agian."
print "Have a nice day!"

另一个循环将监控所有硬件并在出现问题时发送电子邮件。

if floatSwitch is True:
    #Write the time and what happened to the file
    log.write(str(now) + "Float switch turned on")
    timeLastOn = now
    #Wait until switch is turned off

    while floatSwitch:
        startTime = time.time()
        if floatSwitch is False:
            log.write(str(now) + "Float switch turned off")
            timeLastOff = now
            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.")
            break

这两个功能都很关键,我希望它们并行运行,那么如何让它们像那样运行呢?感谢大家的帮助!

4

1 回答 1

1

并行运行的东西?尝试使用线程 - 例如参见标准库中的这个模块,或多处理模块。

您将需要为每个 while 循环创建一个线程。

这篇文章有一些很好的例子来说明如何使用线程。

在其他一些注释中,我不禁注意到您使用if variable is True:了代替if variable:if variable is False:代替if not variable:,给出的替代方案更正常和 Pythonic。

当你这样做时,elif user_input == "exit" or "stop":这将永远是正确的,因为它实际上是在测试 if (use_input == "exit") or ("stop")"stop"是一个非空字符串,因此True在这种情况下它总是会计算为。你真正想要的是elif user_input == "exit" or user_input == "stop":或什至elif user_input in ("exit", "stop"):

最后,当您这样做时log.write(str(now) + "Float switch turned off"),最好进行字符串格式化。你可以这样做log.write("{}Float switch turned off".format(now)),或者使用%(我不知道该怎么做,因为我只使用了几周的 Python 2.x,然后才转到 3.x,它%已被弃用)。

于 2013-10-12T18:07:39.030 回答