import os
import http.server
import socketserver
os.chdir('c:\\Python37')
PORT = 80
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("192.168.0.103", PORT), Handler) as httpd:
print("Serving files from: c:\Python37, on port: ", PORT)
httpd.serve_forever()
This script creates a simple HTTP server that serves files from a specified directory on a specified port. Here's what the code does:
- Imports the
os,http.server, andsocketservermodules. - Changes the current working directory to
'c:\\Python37'using thechdir()function from theosmodule. - Sets the variable
PORTto80, which is the default port number for HTTP traffic. - Defines a variable
Handlerto use theSimpleHTTPRequestHandlerclass from thehttp.servermodule. - Uses the
TCPServerclass from thesocketservermodule to create an instance of a server, passing in a tuple of the IP address and port number as the first argument and theHandlervariable as the second argument. This creates a TCP server that listens for incoming requests on the specified IP address and port number, and uses the specifiedHandlerto handle each request. - Prints a message to the console to indicate that the server is ready and listening for requests.
- Calls the
serve_forever()method on thehttpdobject, which starts the server and listens for incoming requests indefinitely, until the server is shut down.
Once the server is running, any files in the 'c:\\Python37' directory can be accessed by navigating to the server's IP address in a web browser, using the port number specified in the script (in this case, 80).