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

14

我正在尝试弄清楚如何在运行"".serve_forever()方法后将过载的自定义BaseHTTPServer实例在后台运行。

通常情况下,当您运行该方法时,执行会挂起直到执行键盘中断,但我希望它能在后台服务请求,同时继续脚本执行。请帮忙!

2个回答

16

你可以在不同的线程中启动服务器:https://docs.python.org/3/library/_thread.html#thread.start_new_thread

因此,代码大致如下:

import _thread as thread

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!')

2

我试图使用async进行一些长期的动画,本来认为我需要重写服务器以使用aiohttp(https://docs.aiohttp.org/en/v0.12.0/web.html),但Oliver的技术使用单独的线程节省了我的所有麻烦。我的代码看起来像这样,其中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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接