0

私は Python プログラムを書いていて、同時に 2 つの while ループを実行したいと考えています。私はPythonにかなり慣れていないので、これは初歩的な間違い/誤解である可能性があります. このプロジェクトでは、Raspberry Pi で排水ポンプを監視して、それが機能していることを確認し、機能していない場合は、指定された受信者に電子メールを送信します。1 つのループは、ユーザーと対話し、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!"

もう 1 つのループは、すべてのハードウェアを監視し、問題が発生した場合に電子メールを送信します。

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

並行して実行しているもの?スレッド化を試してみてください - たとえば、標準ライブラリのこのモジュール、または multiprocessing モジュールを参照してください。

while ループごとにスレッドを作成する必要があります。

この投稿には、スレッドの使用方法の良い例がいくつかあります。

他のいくつかのメモでは、if variable is True:代わりにif variable:if variable is False:の代わりにを使用していることに気付かずにはいられませんif not variable:。指定された代替は、より通常の Pythonic です。

elif user_input == "exit" or "stop":実際に if をテストしているため、これを行うと常に true になります(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を数週間しか使用しなかったため、その方法はわかりません)。%

于 2013-10-12T18:07:39.030 に答える