Skip to content

Instantly share code, notes, and snippets.

@cloderic
Last active December 16, 2015 09:09
Show Gist options
  • Save cloderic/5410741 to your computer and use it in GitHub Desktop.
Save cloderic/5410741 to your computer and use it in GitHub Desktop.
Tiny HTTP server in python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
# Version 2, December 2004
#
# Copyright (C) 2013 Clodéric Mars <cloderic.mars@masagroup.net>
#
# Everyone is permitted to copy and distribute verbatim or modified
# copies of this license document, and changing it is allowed as long
# as the name is changed.
#
# DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
# TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
#
# 0. You just DO WHAT THE FUCK YOU WANT TO.
import os
import argparse
import SimpleHTTPServer
import BaseHTTPServer
defaultDirectory = "./"
defaultHost = "127.0.0.1"
defaultPort = 4000
def main():
parser = argparse.ArgumentParser(description="Tiny HTTP server")
parser.add_argument("--directory", help="Served directory (default is {})".format(defaultDirectory), default=defaultDirectory)
parser.add_argument("--host", help="Host to use (default is {})".format(defaultHost), default=defaultHost)
parser.add_argument("--port", help="Port to use (default is {})".format(defaultPort), type=int, default=defaultPort)
args = parser.parse_args()
cwd = os.getcwd()
os.chdir(args.directory)
httpd = BaseHTTPServer.HTTPServer((args.host, args.port), SimpleHTTPServer.SimpleHTTPRequestHandler)
sa = httpd.socket.getsockname()
print "Serving {} on http://{}:{}".format(os.getcwd(), sa[0], sa[1])
try:
httpd.serve_forever()
except KeyboardInterrupt:
print "Server shutting down"
httpd.socket.close()
os.chdir(cwd)
if __name__ == "__main__" :
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment