你几乎就在那里:只需要“转义”引号(即使用print \"
而不是print "
等)来获得第一行的权利:
import os, multiprocessing
p = os.system("ps aux|awk 'NR > 0 { s +=$3 }; END {print \"cpu %\",s}'")
您应该认识到该os.system
命令返回“返回码”——“此过程是否正常结束?”问题的答案。因此, 的值p
是0
“无错误”,而不是变量中的 cpu 负载s
。不知道为什么你需要它两次,因为你已经打印出来了。将最后一行更改为
print "Cores:", multiprocessing.cpu_count(), '\n'
输出变成这样:
cpu% 65.7
Cores: 2
如果您真的想将系统命令的输出直接放入变量中,您可以查看对这个较早问题的答案- 它向您展示了如何使用subprocess.Popen()
和proc.communicate()
做到这一点。但只是让命令行正确(带有转义的引号)是最关键的修复。
更新Popen() 和 system() 方法的两个完整且有效的示例如下:
import os, multiprocessing, subprocess
# two ways to get CPU load and number of CPUs
# command line string to obtain CPU load:
commandString = "ps aux|awk 'NR > 0 { s+=$3 }; END {print \"CPU%\", s}'"
print "Command string used to obtain CPU load:"
print commandString, "\n"
# obtain number of CPUs from the multiprocessing function:
numCPUs = multiprocessing.cpu_count()
# method 1: issue an os.system command, have the result echoed directly to output:
print "Method 1:"
p = os.system(commandString)
print "Cores:", numCPUs, "\n"
# method 2: return the value to a python variable:
cpu = subprocess.Popen(commandString, stdout=subprocess.PIPE, shell=True)
(out, err) = cpu.communicate()
print "Method 2:"
print "Load: ", out,
print "Cores:", multiprocessing.cpu_count(), '\n'
上述输出:
Command string used to obtain CPU load:
ps aux|awk 'NR > 0 { s+=$3 }; END {print "CPU%", s}'
Method 1:
CPU% 18.5
Cores: 2
Method 2:
Load: CPU% 24.1
Cores: 2