【问题标题】:Python If-Condition with While-True Infinite Loop ConflictPython If-Condition 与 While-True 无限循环冲突
【发布时间】:2021-10-31 03:56:57
【问题描述】:

我想问一下,我现在在做python3 http web server。然而,当它停留在“while-true”时,它在“if-condition”上有问题。当我想使用其他“if条件”时,程序卡在“while-true”,无法继续其他程序。

from http.server import BaseHTTPRequestHandler, HTTPServer
import subprocess


Request = None

class RequestHandler_httpd(BaseHTTPRequestHandler):
  def do_GET(self):
    global Request
    messagetosend = bytes('Hello Worldddd!',"utf")
    self.send_response(200)
    self.send_header('Content-Type', 'text/plain')
    self.send_header('Content-Length', len(messagetosend))
    self.end_headers()
    self.wfile.write(messagetosend)
    Request = self.requestline
    Request = Request[5 : int(len(Request)-9)]
    print(Request)
    if Request == 'onAuto':
        
        def always_run():
            subprocess.run("python3 satu.py ;", shell=True)
            subprocess.run("python3 dua.py ;", shell=True)
            
        while True:
            always_run() #the program stuck here and other if cannot be used
        
    
    if Request == 'onFM':
        subprocess.run("python3 satu.py ;", shell=True)
      
    if Request == 'onQR':
        subprocess.run("python3 dua.py ;", shell=True)
      
    if Request == 'offSYS':
        subprocess.run("python3 OFF_SYSTEM.py ;", shell=True)
      
    return


server_address_httpd = ('X.X.X.X',8080) #my private address
httpd = HTTPServer(server_address_httpd, RequestHandler_httpd)
print('Starting Server')
httpd.serve_forever()

【问题讨论】:

  • 查看subprocess.Popen()
  • 谢谢楼主,我试试

标签: python-3.x http if-statement while-loop subprocess


【解决方案1】:

正如 JonSG 评论的那样。你的

while True:
   always_run()

正在阻止您的代码的进一步执行。所以你必须在一个单独的线程中运行它:

import threading

class AlwaysThread(threading.Thread):
   def __init__(self):
      super(AlwaysThread, self).__init__()
      self.stopThread = False

   def run(self):
      self.stopThread = False
      while not self.stopThread:
         always_run()

# where you previously have done the endless loop
t = AlwaysThread()
t.start()

# stop it with t.stopThread = True

我也会使用 switch 语句而不是 if cascade

【讨论】:

  • 谢谢先生,我已经尝试过了。最后!它可以运行。但是如何停止/终止该线程?
  • 非常感谢先生!我会努力的
猜你喜欢
  • 2021-10-22
  • 2017-10-12
  • 2020-11-30
  • 2015-05-22
  • 1970-01-01
  • 1970-01-01
  • 2022-11-23
  • 2014-07-30
  • 1970-01-01
相关资源
最近更新 更多