0

我正在尝试将数据发送到 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()
4

1 回答 1

2

如果您只是想一次发送所有数据,您应该意识到您实际上并没有发送字典,而是发送了一个字符串。在这种情况下,您可以轻松地一次性发送所有数据,只需像这样构建数据:

data = "\n".join([json.dumps(stat._asdict()) for stat in cpuStats])

如果该端点是其他人的,这可能不明智,但假设这是您自己的端点,那么您指向它应该很容易解开这些数据。

此外,我强烈建议requests通过 urllib 切换到模块,因为它在更简单的包装器中扩展了所有相同的功能。例如,requests您将通过执行以下操作发送该请求:

import requests

response = requests.post("your://url.here", data=data)
print response.content
于 2013-09-12T02:40:18.653 回答