本文介绍了通过 Python 子进程模块在 shell 中管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图查询给定机器上的前 3 个 CPU 密集型"进程,我发现这个 shell 命令可以做到这一点:ps -eo pcpu,pid,user,args |排序 -k 1 -r |头-3

So I'm trying to query for the top 3 CPU "intensive" processes on a given machine, and I found this shell command to do it: ps -eo pcpu,pid,user,args | sort -k 1 -r | head -3

我想在 Python 脚本中使用这些数据,所以我需要能够通过 subprocess 模块捕获上述命令的输出.以下工作,但只返回一个巨大的字符串,因为我没有将它限制在前 3 位:

I want to use this data inside a Python script, so I need to be able to capture the output of the above command via the subprocess module. The following works, but just returns a huge string since I'm not restricting it to the top 3:

psResult = subprocess.check_output(['ps', '-eo', 'pcpu,user,args'])

我不太确定这个 subprocess.check_output 是如何工作的.我尝试了一次微不足道的尝试:

I'm not quite sure how this subprocess.check_output works.. in a meager attempt I tried:

subprocess.check_output(['ps', '-eo', 'pcpu,user,args', '|', 'sort', '-k', '1', '-r','|', 'head', '-3'])

这给了我一个错误:ps:非法参数:|

如何在 Python 中使用管道 | 符号,或使用其他方式进行排序,而无需对 psResult = subprocess 返回的巨大字符串进行大量解析.check_output(['ps', '-eo', 'pcpu,user,args'])?

How do I use the pipe | symbol inside Python, or use some other way to do the sorting without having to do incredible amounts of parsing on the huge string returned by psResult = subprocess.check_output(['ps', '-eo', 'pcpu,user,args'])?

谢谢!问候,-kstruct

Thanks!Regards,-kstruct

推荐答案

您可以传递 shell=True 参数来执行纯 shell 命令:

You can pass the shell=True argument to execute the plain shell command:

import subprocess
subprocess.check_output('ps -eo pcpu,pid,user,args | sort -k 1 -r | head -3',
                        shell=True)

或者,使用 ps 的排序选项和 Python 的内置字符串函数,如下所示:

Alternatively, use the sorting options of ps and Python's built-in string functions like this:

raw = subprocess.check_output('ps -eo pcpu,pid,user,args --sort -pcpu')
first_three_lines = list(raw.split('
'))[:3]

这篇关于通过 Python 子进程模块在 shell 中管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 11:03
查看更多