2013-10-12 123 views
0

我正在編寫一個Python程序,並且我想同時運行兩個while循環。我對Python很新,所以這可能是一個基本的錯誤/誤解。該項目正在建立一個樹莓派監控器,以確保它正在工作,如果沒有,請發送電子郵件給指定的收件人。一個循環將與用戶交互,並通過SSH實時響應發送給它的命令。並行while循環

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 

這兩個函數都很重要,我希望它們能夠並行運行,所以如何讓它們像這樣運行?感謝大家的幫助!

+2

查看'multiprocessing'和/或'threading'模塊。 – roippi

回答

0

東西並行?嘗試使用線程 - 請參閱標準庫中的this模塊或多處理模塊。

您將需要爲每個while循環創建一個線程。

This後有一些很好的如何使用線程的例子。

在其他一些筆記,我不禁注意到您使用if variable is True:代替if variable:if variable is False:,而不是if not variable:,給予更加正常和Python的替代品。

當你做elif user_input == "exit" or "stop":這將永遠是真實的,因爲它實際上是測試如果(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)),或者使用%(我不知道該怎麼做,因爲我在轉移到3.x之前只使用了Python 2.x幾個星期,其中%已被棄用)。