Python BaseHTTPServer:如何让它停止? [英] Python BaseHTTPServer: How to get it to stop?

查看:29
本文介绍了Python BaseHTTPServer:如何让它停止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据来源,BaseServer.shutdown() 必须从与运行服务器的线程不同的线程调用.

但是,我正在尝试使用在 Web 请求中提供给服务器的特定值来关闭服务器.

请求处理程序显然在这个线程中运行,所以在我这样做之后它仍然会死锁:

httpd = BaseHTTPServer.HTTPServer(('', 80), MyHandler)print("在线程中启动服务器")threading.Thread(target=httpd.serve_forever).start()

我怎样才能完成我想要的?我是否必须设置套接字或管道或其他东西(请告诉我如何执行此操作,如果是解决方案),主线程可以在其中阻塞并等待子线程发送消息,此时它将能够调用shutdown()?

我目前能够通过从请求处理程序调用httpd.socket.close()"来实现某种工作"行为.这会生成 [Errno 9] Bad file descriptor 错误,并且似乎终止了 Windows 上的进程.

但这显然不是解决此问题的正确方法.

更新大约.2013 年 8 月 我已经使用 node.js 来满足对强大的异步 I/O 的需求,但是大量的副项目(例如线性代数研究、各种命令行工具前端)让我又回到了 python.回顾这个问题,BaseHTTPServer 与其他选项(例如 Phil 提到的各种微框架)相比,可能没有多少实用价值.

解决方案

线程.事件对于向其他线程发送信号很有用.例如,

please_die = threading.Event()# 在处理程序中please_die.set()# 在主线程please_die.wait()httpd.shutdown()

如果您想在线程之间发送数据,您可以使用 队列.>

According to the source the BaseServer.shutdown() must be called from a different thread than the one the server is running on.

However I am trying to shut down the server with a specific value provided to the server in a web request.

The request handler obviously runs in this thread so it will still deadlock after I have done this:

httpd = BaseHTTPServer.HTTPServer(('', 80), MyHandler)
print("Starting server in thread")
threading.Thread(target=httpd.serve_forever).start()

How can I accomplish what I want? Must I set up a socket or pipe or something (please show me how to do this, if it is the solution), where the main thread can block and wait on the child thread to send a message, at which point it will be able to call shutdown()?

I am currently able to achieve some "kind of works" behavior by calling "httpd.socket.close()" from the request handler. This generates an [Errno 9] Bad file descriptor error and seems to terminate the process on Windows.

But this is clearly not the right way to go about this.

Update ca. Aug. 2013 I have eloped with node.js to fill the need for robust async I/O, but plenty of side projects (e.g. linear algebra research, various command line tool frontends) keep me coming back to python. Looking back on this question, BaseHTTPServer probably has little practical value comparatively to other options (like various microframeworks that Phil mentions).

解决方案

threading.Event is useful for signalling other threads. e.g.,

please_die = threading.Event()

# in handler
please_die.set()

# in main thread
please_die.wait()
httpd.shutdown()

You might use a Queue if you want to send data between threads.

这篇关于Python BaseHTTPServer:如何让它停止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆