首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python If-Condition with While-True无限循环冲突

Python If-Condition with While-True无限循环冲突
EN

Stack Overflow用户
提问于 2021-09-01 16:11:09
回答 1查看 58关注 0票数 0

我想问一下,现在我正在做python3 http web服务器。然而,当它停留在“while-true”时,它在“if-condition”上有问题。当我想使用其他“if条件”时,程序停留在“while-true”,不能继续执行其他程序。

代码语言:javascript
运行
复制
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()
EN

Stack Overflow用户

发布于 2021-09-01 19:21:04

正如JonSG评论的那样。你的

代码语言:javascript
运行
复制
while True:
   always_run()

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

代码语言:javascript
运行
复制
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

票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69017296

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档