Os:windows 8.1 with Update
Keywords: Python3.4, http.server, Thread
The example code is as follows:
ImportOS fromThreadingImportThreadImport TimeImportWebbrowserport_number="8000"defrun_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 # does not make us wait for you to exitServer.start () time.sleep (2)#Wait to start the server firstdeftest (): URL="http://localhost:"+port_number webbrowser.open (URL)Print(URL +"is opened in browser") test ()
Code Explanation:
1. Os.system ("python-m http.server" + port), "python -m http. " Server 8000"is a cmd that can start an HTTP server.
2. Server = Thread (target=run_on, Args=[port_number]), create a thread to start the HTTP server. If you start the HTTP server in the main thread, it will block the main thread and not execute the code below.
3. Server.start (), start the thread.
4. Time.sleep (2), waiting for HTTP server to start.
5. Webbrowser.open (URL), open the URL.
Reference:
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 multithreaded Boot Http.server