的输出
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都被占用时等待。在
有什么建议吗?在
非常感谢!在
如果您要用一个大shell命令来完成这一切,只需将} 中,这样它将为您提供行数而不是实际的行数:
-c
参数添加到^{当然,您可以通过在末尾添加
| wc -l
,或者通过计算Python中的行数来使这变得更复杂,但是为什么呢?在或者,为什么还要涉及到外壳呢?您可以像运行
^{pr2}$grep
一样轻松地在Python中进行搜索,这样就不会出现这样的问题,即您无意中创建了一个grep
进程,ps
将重复该进程以匹配您的搜索,然后需要grep -v
返回:或者,更简单地说,不要要求
ps
给你一大堆你不想要的信息,然后想办法忽略它,只需要问你想要的信息:或者,更简单地说,安装^{} ,甚至不要尝试运行子进程并解析其输出:
如果要模拟管道,可以使用Popen:
或者使用pgrep(如果可用):
^{pr2}$由于pgrep只获取可执行文件的名称,因此两者的输出可能不同,但ps-aux vs ps-a也会得到不同的输出
相关问题 更多 >
编程相关推荐