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.
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)
subprocess.Popen
instead ofos.system
, it offers a lot of additional functionality including termination of the spawned subprocess. Or you could justimport SimpleHTTPServer
and use it directly in your script... – Knowlesubprocess
documentation has all the info you need, see the sections about thePopen
constructor and usingPopen
objects - you could do something likeserver = Popen(["python", "-m", "SimpleHTTPServer"])
and then useserver.terminate()
orserver.kill()
to end the process. As for starting aSimpleHTTPServer
in a script, just look at theif __name__ == "__main__":
block in SimpleHTTPServer.py - just keep a reference to the BaseServer instance and close it (it's a TCPServer subclass, so the TCPServer docs should help). – Knowle