標籤:
OS: Windows 8.1 with update
關鍵字:Python3.4, http.server, Thread
例子代碼如下:
import osfrom threading import Threadimport timeimport webbrowserport_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 firstdef 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。
參考:
https://docs.python.org/3/library/http.server.html#http.server.HTTPServer
https://docs.python.org/3/library/threading.html?highlight=thread#module-threading
Python多線程啟動http.server