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)
My solution with browser opening:
File: http.py
After, just run:
Here is what I am doing:
If you call
fin
in your program, then the server shuts down.This is a closure solution to the problem. Works on python 3.
simple_http_server
which will returnstart
andstop
functionswhich you can use as
In my opinion, what I did is:
(only if you ran the cmd/terminal command in python, because I think the way to stop it in cmd/terminal is ctrl+c or just quit the cmd/terminal)
note: the pid is also there
Hope this helps :D!!
A slight modification to User's code above:
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.