繁体   English   中英

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

[英]Run Python HTTPServer in Background and Continue Script Execution

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

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

您可以在不同的线程中启动服务器: https : //docs.python.org/2/library/thread.html

所以像:

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

我试图使用 async 做一些长期动画,并认为我必须重写服务器才能使用 aiohttp ( https://docs.aiohttp.org/en/v0.12.0/web.html ),但 Olivers 技术使用单独的线程为我节省了所有的痛苦。 我的代码看起来像这样,其中 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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM