简体   繁体   English

python子进程中的子shell

[英]Subshell in python subprocess

Within a python script I need to launch a command such as 在python脚本中,我需要启动一个命令,例如

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 ) 使用子进程,我尝试使用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. subprocess.run带有一个可选的shell=True参数,它将在子shell中运行您的命令。 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: 另一个(更好的,imo)解决方案是使用psutil软件包和os.kill ,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM