How can I kill SimpleHTTPServer from a Python script?

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

I did a test script to just start the server, get the page and prove that the server is running, and then stop the server. It seems I can not get the pid of the server. When I try to kill pid that this script report is run after the script, I get a message that there is no such process; but the server is still running.

How to get the correct pid for a server or, more generally, how to stop a server from a 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. sleep(1) 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) 
+6
python python-requests
Oct 24 '13 at 15:46
source share
5 answers

That's what I'm doing:

 import threading try: 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 thread.start() def fin(): server.shutdown() print('server running on port {}'.format(server.server_port)) # here is your program 

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

+6
Oct 24 '13 at 18:50
source

A slight modification of the user code above:

 import threading try: 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(): thread.start() print('starting server on port {}'.format(server.server_port)) def down(): server.shutdown() print('stopping server on port {}'.format(server.server_port)) 
+3
Feb 11 '15 at 19:47
source

I managed to run this, but I'm curious to know how this compares with the user response above. I came up with this by 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. sleep(1) url = 'http://localhost:8000/index.html' print "Testing request: ", url r = requests.get(url) print "Status code: ", r.status_code os.killpg(pro.pid, signal.SIGTERM) 
+1
Oct 24 '13 at 23:34
source

My solution with opening a browser:

File: http.py

 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 self.run = 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" else: print("Chrome not found!") def start(self): self.run = 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) self.thread.start() webbrowser.get(str(self.browser_path)).open(self.url+":"+str(self.port)+"/") def _serve(self): while self.run: self.httpd.handle_request() def stop(self): self.run = False self.httpd.server_close() 

After that, just run:

 from http import HTTPServer server = HTTPServer() server.start() raw_input("Enter to close") server.stop() 
0
Sep 03 '15 at 16:57
source

This is a solution to the closure problem. Powered by 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(): os.chdir(path) thread.start() webbrowser.open_new_tab('http://{}:{}'.format(host, port)) print('starting server on port {}'.format(server.server_port)) def stop(): os.chdir(cwd) server.shutdown() server.socket.close() print('stopping server on port {}'.format(server.server_port)) return start, stop 

simple_http_server , which will return the 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 127.0.0.1 - - [14/Aug/2016 17:49:31] "GET / HTTP/1.1" 200 - >>> stop() stopping server on port 4005 
0
Aug 14 '16 at 2:09
source



All Articles