Python subprocess.run() to for: kill -HUP `ps -C gunicorn fch -o pid | head -n 1`

Viewed 116

I need a Python script subprocess.run() call for the following:

kill -HUP `ps -C gunicorn fch -o pid | head -n 1`

This can't be one long concatenation

subprocess.run(["kill","-HUP","ps","-C","gunicorn","fch","-o","pid","|","head","-n","1"])

How to read the ps -C gunicorn fch -o pid | head -n 1 portion into subprocess.run so it is interpreted by "kill","-HUP" as a quoted string?

1 Answers

The backticks in your original shell code makes a whole separate subprocess for the call to ps. The pipe actually does another process creation, for head!

If you want to do that in pure Python (rather than delegating it all to a shell), you probably want to do at least one additional subprocess call. You probably don't need the one for head, since you can easily read one line of output yourself inside Python.

Try something like:

ps_process = subprocess.Popen(["ps","-C","gunicorn","fch","-o","pid"],
                              stdout=subprocess.PIPE)
pid_string = next(ps_process.stdout).decode().strip()
subprocess.run(["kill","-HUP", pid_string])

It's also possible that you can send the HUP signal directly from Python, rather than by calling the kill program. And heck, there's probably a module that would let you look up the PIDs of other running programs.

Related