1

複数回試行しても、このコードは失敗します。私がやろうとしているのは、「cpu stats」を JSON としてサーバーに送信することです。問題は、cpustats だけで問題ありません。異なる cpupercentages (ユーザー、アイドルなど) を持つ名前付きタプルが 1 つだけあります。しかし、「percpu」は、各 cpu の名前付きタプル (ユーザー、アイドルなど) のリストを返します。そのため、リストを辞書に変換できません。リストをループして、名前付きタプルのそれぞれをサーバーに送信しようとしています。(参考までに-私は2.7.5を使用しています)。スクリプトは、ループや試行/例外を試行せずに正常に機能しました。「200 OK」が返されました。しかし、今それを実行すると、エラー、応答メッセージ/ステータスさえ返されません。スクリプトが try/except ブロック全体をバイパスしているように見えます。最後の「print cpuStats」行だけで、期待どおりに配信されます。

    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)
    print cpuStats
    def loop_thru_cpus():

       for i in cpuStats:

         cpuStats = cpuStats[i]
         cpuStats = json.dumps(cpuStats._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': cpuStats, 'thisClient': 1234})
             headers = httplib.HTTPConnection(serverHost, port)
             conn.request("POST", "", params, headers)
             response = conn.response()
         print response.status, response.reason

    except IndexError:
            break

        i = i+1

    s.close()
4

1 に答える 1