Python多线程启动http.server
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 = "8000"
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。
评论关闭