Want to create your own webserver in a single line of Python code? No problem, just use this command in your shell:
$ python -m http.server 8000
The terminal will tell you:
Serving HTTP on 0.0.0.0 port 8000
To shut down your webserver, kill the Python program with CTRL+c
.
This works if you’ve Python 3 installed on your system. To check your version, use the command python --version
in your shell.
You can run this command in your Windows Powershell, Win Command Line, MacOS Terminal, or Linux Bash Script.
You can see in the screenshot that the server runs on your local host listening on port 8000 (the standard HTTP port to serve web requests).
Note: The IP address is NOT 0.0.0.0—this is an often-confused mistake by many readers. Instead, your webserver listens at your “local” IP address 127.0.0.1 on port 8000. Thus, only web requests issued on your computer will arrive at this port. The webserver is NOT visible to the outside world.
Python 2: To run the same simple webserver on Python 2, you need to use another command using SimpleHTTPServer
instead of http
:
$ python -m SimpleHTTPServer 8000 Serving HTTP on 0.0.0.0 port 8000 ...
If you want to start your webserver from within your Python script, no problem:
import http.server import socketserver PORT = 8000 Handler = http.server.SimpleHTTPRequestHandler with socketserver.TCPServer(("", PORT), Handler) as httpd: print("serving at port", PORT) httpd.serve_forever()
You can execute this in our online Python browser (yes, you’re creating a local webserver in the browser—how cool is that)!
This code comes from the official Python documentation—feel free to read more if you’re interested in setting up the server (most of the code is relatively self-explanatory).
Related Resources:
- Python One Line X
- Pythononeliners.com
- Book “Python One-Liners” (Amazon Link)
- Python One Line For Loop
- Python Quicksort One Line
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.