How do I kill SimpleHTTPServer from within a Python script?

python simplehttpserver
python basehttprequesthandler
python file server
python -m simplehttpserver directory
how to create a web server in python
python http server ip address
python3 simple http server
python server example

I am trying to use http.server to test all the links in a Python project. I can get my script to work if I start the server before running my script, and then the server stops when I close the terminal window. But I'd really like the script itself to start and stop the server.

I made a test script to simply start the server, get a page and prove the server is running, and then stop the server. I can't seem to get the pid of the server. When I try to kill the pid that this script reports after the script runs, I get a message that there is no such process; but the server is still running.

How do I get the correct pid for the server, or more generally how do I stop the server from the script?

import os
import requests
from time import sleep

# Start server, in background.
print("Starting server...")
os.system('python -m http.server &')
# Make sure server has a chance to start before making request.

print "Server pid: "
os.system('echo $$')

url = 'http://localhost:8000/index.html'
print("Testing request: ", url)
r = requests.get(url)
print("Status code: ", r.status_code)

Here is what I am doing:

import threading

    from http.server import HTTPServer, SimpleHTTPRequestHandler # Python 3
except ImportError: 
    from SimpleHTTPServer import BaseHTTPServer
    HTTPServer = BaseHTTPServer.HTTPServer
    from SimpleHTTPServer import SimpleHTTPRequestHandler # Python 2

server = HTTPServer(('localhost', 0), SimpleHTTPRequestHandler)
thread = threading.Thread(target = server.serve_forever)
thread.daemon = True

def fin():

print('server running on port {}'.format(server.server_port))

# here is your program

If you call fin in your program, then the server shuts down.

How do I shut down a python simpleHTTPserver?, MYPORT=8888; kill -9 `ps -ef |grep SimpleHTTPServer |grep $MYPORT The above has been tested in Mac OS, but as far as I can remember it works just the Using a script to start it will put the process out of reach of jobs . Running a Python SimpleHTTPServer in the background and killing it when doneSimpleHTTPServer -

A slight modification to User's code above:

import threading
  from http.server import HTTPServer, BaseHTTPRequestHandler # Python 3
except ImportError: 
  import SimpleHTTPServer
  from BaseHTTPServer import HTTPServer # Python 2
  from SimpleHTTPServer import SimpleHTTPRequestHandler as BaseHTTPRequestHandler
server = HTTPServer(('localhost', 0), BaseHTTPRequestHandler)
thread = threading.Thread(target = server.serve_forever)
thread.deamon = True
def up():
  print('starting server on port {}'.format(server.server_port))
def down():
  print('stopping server on port {}'.format(server.server_port))

Serving Files with Python's SimpleHTTPServer Module, In this article, we'll use the SimpleHTTPServer module to quickly run a Python app and access it At times like this we can instead use the server directly in our code using the In these cases you need to call server_close() to stop the server . Python SimpleHTTPServer Status Step 3: Changing SimpleHTTPServer Port. 8. By default python’s SimpleHTTPServer serves files and directories through port 8000, but you can define a different port number (Here I am using port 9999) as you desire with the python command as shown below. # python –m SimpleHTTPServer 9999

I got this to run, but I'm curious to hear how this compares to User's answer above. I came up with this after looking at the accepted answer here.

import subprocess
import requests
import os
import signal
from time import sleep

print "Starting server..."
cmd = 'python -m SimpleHTTPServer'
pro = subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid)

# Make sure server has a chance to start before making request.

url = 'http://localhost:8000/index.html'
print "Testing request: ", url
r = requests.get(url)
print "Status code: ", r.status_code

os.killpg(, signal.SIGTERM)

How can I start the python SimpleHTTPServer on port 80?, sudo python -m http.server 80. Ports below 1024 require root privileges. As George added in a comment, running this command as root is not a good idea - it � $ python -m SimpleHTTPServer 8080 How to share files and directories. In your terminal, cd into whichever directory you wish to have accessible via browsers and HTTP. cd /var/www/ $ python -m SimpleHTTPServer After you hit enter, you should see the following message: Serving HTTP on port 8000 …

My solution with browser opening:


import SimpleHTTPServer
import SocketServer
import threading
import webbrowser
import platform
from socket import SOL_SOCKET,SO_REUSEADDR

class HTTPServer():

    def __init__(self,port=8000,url='http://localhost'):
        self.port = port
        self.thread = None
        self.httpd = None                = False
        self.url = url

        os = platform.system()
        if os=='Linux':
            self.browser_path = "/usr/bin/google-chrome %s"            
        elif os == 'Windows':
            self.browser_path = "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s"   
            print("Chrome not found!")

    def start(self):        = True     
        self.httpd = SocketServer.TCPServer(("", self.port), SimpleHTTPServer.SimpleHTTPRequestHandler)
        self.httpd.socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
        self.thread = threading.Thread(target = self._serve)

    def _serve(self):        

    def stop(self): = False

After, just run:

from http import HTTPServer

server = HTTPServer()

raw_input("Enter to close")


Option 1: Use the Python localhost Server - DUSPviz, XAMPP will mimic what MIT Scripts or a commercial hosting provider can serve. Python comes with a simple built in HTTP server that can run static webpages. cd /document/mywebsite $ python -m SimpleHTTPServer Serving HTTP on 0.0. 0.0 port When done working on your web site, stop your server using CTRL-C� You can actually start a web server with python without even having to write any scripts. Just go to your terminal and do the following (but make sure you are on python 3) python -m http.server 8080. By default, this server will be listening on all interfaces and on port 8080. If you want to listen to a specific interface, do the following:

This is a closure solution to the problem. Works on python 3.

import os
import threading
import webbrowser
from http.server import HTTPServer, SimpleHTTPRequestHandler

def simple_http_server(host='localhost', port=4001, path='.'):

    server = HTTPServer((host, port), SimpleHTTPRequestHandler)
    thread = threading.Thread(target=server.serve_forever)
    thread.deamon = True

    cwd = os.getcwd()

    def start():
        webbrowser.open_new_tab('http://{}:{}'.format(host, port))
        print('starting server on port {}'.format(server.server_port))

    def stop():
        print('stopping server on port {}'.format(server.server_port))

    return start, stop

simple_http_server which will return start and stop functions

>>> start, stop = simple_http_server(port=4005, path='/path/to/folder')

which you can use as

>>> start()
starting server on port 4005 - - [14/Aug/2016 17:49:31] "GET / HTTP/1.1" 200 -

>>> stop()
stopping server on port 4005

Identifying and killing background Python processes, I started a simple Python http server as a background process at the end of a Python script. Here is how to identify and kill background Python processes in Let's say I want to kill the python -m SimpleHTTPServer process. I have a script named which is not in a module. It just has code that should execute when the script itself is run. There are no functions, classes, methods, etc. I have another script which

Extending Python's Simple HTTP Server, Open the file in the editor of your choice and then add the following import statements: Python. xxxxxxxxxx. 1 Add the following code to your wasm-server. py file after the import statements: Python. x. 1 Press Ctrl+C to stop. Python SimpleHTTPServer supports only two HTTP methods – GET and HEAD. So it’s an excellent tool to share files over the network. Python SimpleHTTPServer has been migrated to python http.server module in Python 3, we will learn about both of these modules today and see how easy it is to work with them. If you want to start a server on

Running a Python SimpleHTTPServer in the background and killing , Running a Python SimpleHTTPServer in the background and killing it when python -m SimpleHTTPServer 8000 &> /dev/null & Output on running script:. $ python $ python How do I kill specific python script from another script? I want to kill "python" process, but don't want to kill "python" process. $ killall python kill all python programs $ killall cannot find process You may say that try to kill <PID>, but how do I know pid of "python

Python development web server for Windows � GitHub, This is a simple Python script to serve static files from any project directory, useful when doing web development. Usage. Simply put and server.cmd in a directory, for instance C:\Users\YourName\bin Use Ctrl+C to stop the server. server.cmd. python "%~dp0\" %*. import SimpleHTTPServer . The instructions for the web server depend on what Python version you have default (e.g. 2 or 3). This is how you check : $ python -V Notice the capitalized v, the non-capitalized option will start a Python console in verbose mode; use 'quit()' to exit Python 2.x The Python module we're gonna use here is SimpleHTTPServer.

  • You could use subprocess.Popen instead of os.system, it offers a lot of additional functionality including termination of the spawned subprocess. Or you could just import SimpleHTTPServer and use it directly in your script...
  • That is helpful, but do you mind saying a little more? The only references I seem to find about using SimpleHTTPServer talk about using it from the command line; I'm not quite sure how to stop and start the server from within a python script. I have also never used processes before, so I'm not quite sure how to start the server subprocess, and then stop it. Actively googling...
  • The subprocess documentation has all the info you need, see the sections about the Popen constructor and using Popen objects - you could do something like server = Popen(["python", "-m", "SimpleHTTPServer"]) and then use server.terminate() or server.kill() to end the process. As for starting a SimpleHTTPServer in a script, just look at the if __name__ == "__main__": block in - just keep a reference to the BaseServer instance and close it (it's a TCPServer subclass, so the TCPServer docs should help).
  • I am using Python 2 at the moment, but I'd love this to run on Python 3 as well. I got an error 'no module named HTTPServer', so I changed the Python 2 import to from BaseHTTPServer import HTTPServer. The import worked, but then I got an error that "__init__() got an unexpected keyword argument 'daemon'". I get this if I use my own version of this script, or if I just copy your script and fix the import. Any suggestions?
  • I fixed the deamon argument with an additional line. This should work under Python 3 and 2 now - hopefully.
  • Are you able to kill the server with Ctrl-C?
  • @CiroSantilli巴拿馬文件六四事件法轮功 Since deamon is set to true, the program should finish once the main thread ends. Usually, the main thread can be terminated with Control+C.
  • @User I didn't reproduce on Ubuntu 16.04, Python 2.7, gnome terminal. Nothing happens on Ctrl+C, the server just keeps running, and I have to close the terminal for it to stop.
  • Instead of opening Chrome you can use start %s on Windows and open %s on OSX (not sure for Linux) to open the default browser.
  • And how is this an "internal" approach?
  • well I have the same problem as yours, so I searched what is PID in google and shows the result in google like this:… then I have an idea of just quitting it then it does work lol
  • You're approach is in essence giving the result via an external "forced" process. Teh destinction here is that OP is asking for a solution from within the serverscript. This can be done via threading routines or latest asyncio methods. I don't have that problem and merely reviewed your answer as it was flagged for "low quality answer".. and judging whether it was needed to be removed or not. I hope my comment helps you to carefully look at the question again and revaluate whether your answer provides the correct solution OP was asking for.
  • Ok, I understand :)