Search code examples
pythonpython-2.7subprocesssimplehttpserver

Kill SimpleHTTPServer process which is started in background with subprocess.Popen


I am trying to kill SimpleHTTPServer in my script. Manually the command is working fine.

Starting SimpleHTTPServer in background:
-bash-4.2$ python -m SimpleHTTPServer 8080 &
[1] 26345

Verifying SimpleHTTPServer process:
-bash-4.2$ ps -ef | grep SimpleHTTPServer
x  26345 20169  0 17:44 pts/21   00:00:00 python -m SimpleHTTPServer 8080

Killing SimpleHTTPServer:
-bash-4.2$ kill -9 `ps -ef | grep SimpleHTTPServer | grep 8080 | awk '{print $2}'`

Verifying SimpleHTTPServer is killed or not:
-bash-4.2$ ps -ef | grep SimpleHTTPServer
x  26356 20169  0 17:45 pts/21   00:00:00 grep --color=auto SimpleHTTPServer

Same thing in script is not working. I am using subprocess.Popen.

subprocess.Popen(["kill", "-9", "`ps -ef | grep SimpleHTTPServer | grep 8080 | awk '{print $2}'`"])
(Pdb++) kill: cannot find process "`ps -ef | grep SimpleHTTPServer | grep 8080 | awk '{print $2}'`"

Solution

  • You're trying to use a shell backtick, around a shell pipeline, in that kill command. But you're trying to do it without shell=True. You can't do that.

    You can build a sh command line and run that with shell=True, but that's usually a bad idea.

    The subprocess docs on Replacing Older Functions with the subprocess Module show how you can do the same things in Python that you were using the shell for. That's a better idea, but a bit of work.

    But the simplest thing to do is just not call any of this stuff.

    • You don't need the ps|grep|grep|awk to find the PID of the process, because you Popened the process, so it's just proc.pid.
    • And you don't need the kill either, because you still have that Popen object around, so you can just call kill, terminate, or send_signal on it.