Romain G
Romain G

Reputation: 63

Subshell in python subprocess

Within a python script I need to launch a command such as

kill $(ps aux | grep httpd | awk '{print $2}')

Using subprocess I have tried to split the command using a function from https://stackoverflow.com/a/29755431/1355628)

The function is fine with simple commands with pipe but unfortunately with the one above it does not seem to work (the return code seems to be completely random...)

Thanks is advance

Upvotes: 3

Views: 6269

Answers (1)

iCart
iCart

Reputation: 2351

subprocess.run takes an optional shell=True argument, which will run your command in a subshell. Please do read the Security Considerations however, if you're handling user input.

Another (better, imo) solution, would be to use the psutil package and os.kill, like this:

import psutil
processes = [p for p in psutil.pids() if 'httpd' in psutil.Process(p).name()]
for process in processes:
    os.kill(...)

Upvotes: 5

Related Questions