【问题标题】:Why is the python subprocess output different from the shell?为什么python子进程输出与shell不同?
【发布时间】:2012-06-18 09:30:34
【问题描述】:

我正在使用subprocess 模块来确定进程是否正在运行。但是当查找的进程不存在时,结果就不一样了。

例如在shell中,如果进程python test.py不存在,则ps -ef|grep python|grep test|awk '{print $2}'的输出为空。但是在python中:

cmd="ps -ef|grep python|grep test|awk '{print $2}'"
vp=subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True)
r=vp.communicate()[0]

输出r 不是无。是执行cmd的shell的pid。

那么如何得到想要的结果呢?

【问题讨论】:

  • 我可以推荐 psutil module 来完成此类任务。
  • 只需将 PID 与 os.getpid() 进行比较。如果匹配,您可以忽略它,因为这是您当前的进程。

标签: python shell process awk subprocess


【解决方案1】:

当 shell 子进程运行时,它的参数对ps 可见,因为它们作为命令行传递给sh

shell=True 通过调用 ['/bin/sh', '-c', cmdstring] 工作。

当您在 shell 中键入管道时,管道的每个部分都会单独调用,因此不会在其参数中同时包含“python”和“test”的进程。

您的进程树如下所示:

python script.py
    /bin/sh -c "ps -ef|grep python|grep test|awk '{print $2}'"
        ps -ef
        grep python
        grep test
        awk '{print $2}'

【讨论】:

    猜你喜欢
    • 2016-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-22
    • 2011-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多