我正在尝试将数据发送到 URL。我有一个代码可以为我的 Mac 上的每个 cpu 发送它。但是当前代码循环遍历每个 cpustats 并一个接一个地发送它们。我需要在 1 个 POST 'cycle' 中发送所有这些,但它应该被格式化,以便它像这样发送它 -
cpuStats = {nice: 123.0, idle:123.0....}
cpuStats = {nice: 123.0, idle:123.0....}
cpuStats = {nice: 123.0, idle:123.0....}
等等...
此外,当前代码从我的 Mac 中提取统计信息(每个 cpustat 都显示“200 OK”),但是当我在 Linux、Windows 上运行它时,它只会返回提示而不会给出任何错误或统计信息。我的猜测是它与“socket.error:”处的“中断”有关(我的 Mac 有 4 个 CPU,但我测试它的 Linux 和 Windows 机器各有 1 个。
import psutil
import socket
import time
import sample
import json
import httplib
import urllib
serverHost = sample.host
port = sample.port
thisClient = socket.gethostname()
currentTime = int(time.time())
s = socket.socket()
s.connect((serverHost,port))
cpuStats = psutil.cpu_times_percent(percpu=True)
def loop_thru_cpus():
global cpuStats
for stat in cpuStats:
stat = json.dumps(stat._asdict())
try:
command = 'put cpu.usr ' + str(currentTime) + " " + str(cpuStats[0]) + "host ="+ thisClient+ "/n"
s.sendall(command)
command = 'put cpu.nice ' + str(currentTime) + " " + str(cpuStats[1]) + "host ="+ thisClient+ "/n"
s.sendall(command)
command = 'put cpu.sys ' + str(currentTime) + " " + str(cpuStats[2]) + "host ="+ thisClient+ "/n"
s.sendall(command)
command = 'put cpu.idle ' + str(currentTime) + " " + str(cpuStats[3]) + "host ="+ thisClient+ "/n"
s.sendall(command)
params = urllib.urlencode({'cpuStats': stat, 'thisClient': 1234})
headers = headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
conn = httplib.HTTPConnection(serverHost, port)
conn.request("POST", "", params, headers)
response = conn.getresponse()
print response.status, response.reason
except IndexError:
continue
except socket.error:
print "Connection refused"
continue
print stat
loop_thru_cpus()
s.close()