如何通过Python执行指定ps命令并获取输出?已尝试subprocess未果
在Python中使用subprocess执行带管道的
ps命令 你要执行的命令包含管道操作,用subprocess可以通过两种方式实现:
方法1:直接启用shell执行(简单快捷)
这种方式让subprocess调用系统shell处理管道逻辑,代码最简洁:
import subprocess # 执行带管道的命令并捕获输出 result = subprocess.run( "ps -eo pid,user,ppid,cmd,%mem,%cpu --sort=-%cpu | head", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True ) # 打印命令输出 print(result.stdout) # 若有错误可查看 # print(result.stderr)
shell=True:告知subprocess通过系统shell执行命令,管道|会被shell解析处理text=True:让输出以字符串形式返回(替代旧版universal_newlines=True)stdout=subprocess.PIPE:捕获命令的标准输出
注意:如果命令参数包含不可信用户输入,不建议用这种方式,存在shell注入风险。
方法2:手动创建管道(更安全)
若要避免shell注入风险,可以手动连接两个subprocess进程,模拟管道行为:
import subprocess # 第一步执行ps命令,捕获输出 ps_process = subprocess.run( ["ps", "-eo", "pid,user,ppid,cmd,%mem,%cpu", "--sort=-%cpu"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True ) # 第二步将ps的输出作为head命令的输入 head_process = subprocess.run( ["head"], input=ps_process.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True ) # 打印最终结果 print(head_process.stdout)
这种方式把命令拆分成列表形式(避免shell解析),将第一个进程的stdout作为第二个进程的stdin,既模拟了管道功能,又避免了shell注入风险。
内容的提问来源于stack exchange,提问作者Yasharth Dubey
相关产品推荐
相关产品推荐

