<p>您可以在处理程序中本地启动另一个线程,并从中调用<code>shutdown</code>。</p>
<p>工作演示:</p>
<pre><code> #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import SimpleHTTPServer
import SocketServer
import time
import thread
class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_POST(self):
if self.path.startswith('/kill_server'):
print "Server is going down, run it again manually!"
def kill_me_please(server):
server.shutdown()
thread.start_new_thread(kill_me_please, (httpd,))
self.send_error(500)
class MyTCPServer(SocketServer.TCPServer):
def server_bind(self):
import socket
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind(self.server_address)
server_address = ('', 8000)
httpd = MyTCPServer(server_address, MyHandler)
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
</code></pre>
<p>注意事项:</p>
<ol>
<li>要终止服务器,请执行<code>http://localhost:8000/kill_server</code>请求。</li>
<li>我创建了调用<code>server.shutdown()</code>的函数,并从另一个线程运行它来解决我们讨论的问题。</li>
<li>我使用来自<a href="https://stackoverflow.com/a/18858817/774971">https://stackoverflow.com/a/18858817/774971</a>的建议使socket立即可以重用(您可以再次运行服务器,而不必使用<em>[Errno 98]地址</em>错误)。对于stock TCPServer,您必须等待连接超时才能再次运行服务器。</li>
</ol>