【问题标题】:piping in shell via Python subprocess module通过 Python 子进程模块在 shell 中管道
【发布时间】:2012-05-11 10:35:34
【问题描述】:

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

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

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

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

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

这给了我一个错误:ps: illegal argument: |

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

谢谢! 问候, -kstruct

【问题讨论】:

  • 你可以编写一个shell脚本,其中包含你的带有管道的代码,然后从子进程模块调用它

标签: python shell subprocess pipe


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:

    其他人建议使用shell=True,如果您将受信任的输入传递给shell,this answer 很好。然而,shell=True 引入了一些不安全感。为安全起见,docs 建议如下:

    output=`dmesg | grep hda`
    # becomes
    p1 = Popen(["dmesg"], stdout=PIPE)
    p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
    p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
    output = p2.communicate()[0]
    

    【讨论】:

      【解决方案3】:

      如果你使用它应该可以工作:

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

      然后使用/bin/sh 完全像这样运行命令,因此管道将起作用。

      【讨论】:

        【解决方案4】:

        为什么要使用外部命令?使用psutil

        import psutil
        def cpu_percentage(proc):
            try:
                return proc.get_cpu_percent()
            except psutil.AccessDenied:
                return float('-inf')
        
        top3 = sorted(psutil.process_iter(), key=cpu_percentage, reverse=True)[:3]
        for proc in top3:
            # do whatever
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-03-21
          • 2014-05-29
          • 1970-01-01
          • 1970-01-01
          • 2017-02-18
          • 2015-07-18
          • 1970-01-01
          相关资源
          最近更新 更多