你就快到了:只需要“转义”引号(即使用 print \" 而不是 print " 等)来正确显示第一行:
import os, multiprocessing
p = os.system("ps aux|awk 'NR > 0 { s +=$3 }; END {print \"cpu %\",s}'")
并且您应该认识到os.system 命令返回“返回码”——“此过程是否正常结束?”问题的答案。因此p 的值是0“无错误”,而不是变量s 中的cpu 负载。不知道为什么你需要它两次,因为你已经打印出来了。将最后一行改为
print "Cores:", multiprocessing.cpu_count(), '\n'
输出变成这样:
cpu% 65.7
Cores: 2
如果您真的想将系统命令的输出直接放入变量中,您可以查看this earlier question 的答案——它向您展示了如何使用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