在后台运行Python HTTPServer并继续执行脚本

在后台运行Python HTTPServer并继续执行脚本,python,python-multithreading,basehttpserver,python-daemon,Python,Python Multithreading,Basehttpserver,Python Daemon,在运行“.serve\u forever()方法后,我正在尝试找出如何在后台运行重载的自定义BaseHTTPServer实例 通常,当您运行方法时,执行将挂起,直到您执行键盘中断,但我希望它在继续执行脚本的同时在后台为请求提供服务。请帮忙 您可以在不同的线程中启动服务器: 比如: def start_server(): # Setup stuff here... server.serve_forever() # start the server in a background

在运行“.serve\u forever()方法后,我正在尝试找出如何在后台运行重载的自定义BaseHTTPServer实例


通常,当您运行方法时,执行将挂起,直到您执行键盘中断,但我希望它在继续执行脚本的同时在后台为请求提供服务。请帮忙

您可以在不同的线程中启动服务器:

比如:

def start_server():
    # Setup stuff here...
    server.serve_forever()

# start the server in a background thread
thread.start_new_thread(start_server)

print('The server is running but my script is still executing!')

我试图用异步做一些长期动画,并认为我必须重写服务器以使用aiohttp(),但奥利弗使用分离线程的技术让我省去了所有这些痛苦。我的代码如下所示,其中MyHTTPServer只是我的HTTPServer的自定义子类

import threading
import asyncio
from http.server import BaseHTTPRequestHandler, HTTPServer
import socketserver
import io
import threading

async def tick_async(server):        
    while True:
        server.animate_something()
        await asyncio.sleep(1.0)

def start_server():
    httpd.serve_forever()
    
try:
    print('Server listening on port 8082...')

    httpd = MyHTTPServer(('', 8082), MyHttpHandler)
    asyncio.ensure_future(tick_async(httpd))
    loop = asyncio.get_event_loop()
    t = threading.Thread(target=start_server)
    t.start()
    loop.run_forever()