Python多线程启动http.server

OS: Windows 8.1 with update

关键字:Python3.4, http.server, Thread

例子代码如下:

import os
from threading import Thread
import time
import webbrowser port_number = "" def run_on(port):
os.system("python -m http.server " + port) if __name__ == "__main__":
server = Thread(target=run_on, args=[port_number])
#run_on(port_number) #Run in main thread
#server.daemon = True # Do not make us wait for you to exit
server.start()
time.sleep(2) #Wait to start the server first def test():
url = "http://localhost:" + port_number
webbrowser.open(url)
print(url + " is opened in browser") test()

代码解释:

1. os.system("python -m http.server " + port),“python -m http.server 8000”是一个cmd,能够启动一个http server。

2. server = Thread(target=run_on, args=[port_number]), 创建一个线程用来启动http server。如果启动在主线程里面启动http server,将会阻塞主线程,而不能执行下面的代码。

3. server.start(), 启动线程。

4. time.sleep(2),等待启动http server。

5. webbrowser.open(url), 打开url。

另外一个例子启动/停止服务器

from threading import Thread
import webbrowser, http.server, socketserver
import time; port_number = 8000 server = None
def startServer(port):
Handler = http.server.SimpleHTTPRequestHandler
global server
server = socketserver.TCPServer(("", port), Handler) print("Start server at port", port)
server.serve_forever() def start(port):
thread = Thread(target=startServer, args=[port])
thread.start() startTime = int(time.time())
while not server:
if int(time.time()) > startTime + 60:
print("Time out")
break
return server def stop():
if server:
server.shutdown() def openUrl():
url = "http://localhost:" + str(port_number)
webbrowser.open(url)
print(url + " is opened in browser") if __name__ == "__main__":
start(port_number)
openUrl()

参考:

https://docs.python.org/3/library/http.server.html#http.server.HTTPServer

https://docs.python.org/3/library/threading.html?highlight=thread#module-threading

上一篇:轻易实现基于linux或win运行的聊天服务端程序


下一篇:windows server 2012R2 故障转移集群配置