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


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(...)
链接地址: http://www.djcxy.com/p/77098.html

上一篇: Popen子进程.PIPE及其用途

下一篇: 在python子流程中的子shell