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

问题描述 投票:0回答:3

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

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

python python-multithreading basehttpserver python-daemon
3个回答
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
投票

我试图使用异步做一些长期动画,并认为我必须重写服务器才能使用aiohttp(https://docs.aiohttp.org/en/v0.12.0/web.html),但是奥利弗使用单独线程的技术减轻了我的痛苦。我的代码如下所示,其中 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()

0
投票

另一个使用

concurrent.futures
的示例:

import concurrent.futures
import http.server

def run_http_server():
    port = 8080
    server_address = ('', port)
    httpd = http.server.HTTPServer(server_address, http.server.SimpleHTTPRequestHandler)
    httpd.serve_forever()

def run_parallel_http_server():
    executor = concurrent.futures.ThreadPoolExecutor()
    executor.submit(run_http_server)
    executor.shutdown(wait=False)

if __name__ == '__main__':
    run_parallel_http_server()
    # do something else..
© www.soinside.com 2019 - 2024. All rights reserved.