如何在python中找到运行特定命令的进程数

2024-09-30 14:17:12 发布

您现在位置:Python中文网/ 问答频道 /正文

的输出

ps uaxw | egrep 'kms' | grep -v 'grep'

产量:

^{pr2}$

显然有两个进程在运行程序。我想把这个数字(这里是2)存储为一个变量。关于如何在python中实现这一点有什么建议吗?在

我尝试了以下方法:

procs = subprocess.check_output("ps uaxw | egrep 'kmns' |grep -v 'grep'",shell=True)

但我得到以下结果(我认为当作业当前未运行时,运行作业的进程数为零):

Traceback (most recent call last): File "", line 1, in File "/usr/lib64/python2.7/subprocess.py", line 573, in check_output raise CalledProcessError(retcode, cmd, output=output) subprocess.CalledProcessError: Command 'ps uaxw | egrep 'kmns' |grep -v 'grep'' returned non-zero exit status 1

我该怎么办?在

顺便说一句,我写了一个函数来检测我的系统是否繁忙(这意味着是否安装了cpu总数,以及每个cpu的平均负载是否为0.9):

def busy():
    import subprocess
    output = subprocess.check_output("uptime", shell=False)
    words = output.split()
    sys.stderr.write("%s\n"%(output)) 
    procs = subprocess.check_output("ps uaxw | egrep '(kmns)' | grep -v 'grep'", shell=True)
    kmns_wrds = procs.split("\n")
    wrds=words[9]
    ldavg=float(wrds.strip(','))+0.8
    sys.stderr.write("%s %s\n"%(ldavg,len(kmns_wrds)))
    return max(ldavg, len(kmns_wrds)) > ncpus

上述名称为:

def wait_til_free(myseconds):
    while busy():
        import time
        import sys
        time.sleep(myseconds)
        """ sys.stderr.write("Waiting %s seconds\n"%(myseconds)) """

它基本上告诉系统在所有CPU都被占用时等待。在

有什么建议吗?在

非常感谢!在


Tags: importoutputcheckstderrsysshellgrepwrite
2条回答

如果您要用一个大shell命令来完成这一切,只需将-c参数添加到^{}中,这样它将为您提供行数而不是实际的行数:

$ ps uaxw |grep python |grep -v grep
abarnert         1028   0.0  0.3  2529488  55252 s000  S+    9:46PM   0:02.80 /Library/Frameworks/Python.framework/Versions/3.4/Resources/Python.app/Contents/MacOS/Python /Library/Frameworks/Python.framework/Versions/3.4/bin/ipython3
abarnert         9639   0.0  0.1  2512928  19228 s002  T     3:06PM   0:00.40 /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python /usr/local/bin/ipython2
$
$ ps uaxw |grep python |grep -c -v grep
2

当然,您可以通过在末尾添加| wc -l,或者通过计算Python中的行数来使这变得更复杂,但是为什么呢?在


或者,为什么还要涉及到外壳呢?您可以像运行grep一样轻松地在Python中进行搜索,这样就不会出现这样的问题,即您无意中创建了一个grep进程,ps将重复该进程以匹配您的搜索,然后需要grep -v返回:

^{pr2}$

或者,更简单地说,不要要求ps给你一大堆你不想要的信息,然后想办法忽略它,只需要问你想要的信息:

procs = subprocess.check_output(['ps', '-a', '-c', '-ocomm=']).splitlines()
count = procs.count('kms')

或者,更简单地说,安装^{},甚至不要尝试运行子进程并解析其输出:

count = sum(1 for proc in psutil.process_iter() if proc.name() == 'kms')

如果要模拟管道,可以使用Popen:

p1 = Popen(["ps", "uaxw"], stdout=PIPE)
p2 = Popen(["grep", 'kms'], stdout=PIPE, stdin=p1.stdout)
p1.stdout.close()

out,_ = p2.communicate()
print(len(out.splitlines()))

或者使用pgrep(如果可用):

^{pr2}$

由于pgrep只获取可执行文件的名称,因此两者的输出可能不同,但ps-aux vs ps-a也会得到不同的输出

相关问题 更多 >

    热门问题