After multiple attempts, this code still fails. What I am trying to do is send "cpu stats" as JSON over to the server. The thing is, cpustats alone is fine - there is just 1 namedtuple with the different cpupercentages - user, idle, etc.. But 'percpu' returns a list of each cpu's namedtuple (of user, idle, etc.). So I cannot convert the list to a dictionary. I am trying to loop through the list and then send each one of the namedtuple to the server. (For ref. - I am using 2.7.5). The script worked fine without the attempt to loop and try/except - it returned a '200 OK'. But now when I run it it doesn't even return an error, any response message/status. It's as if the script is just bypassing the whole try/except block. Just the 'print cpuStats' line at the end delivers as it should. (The indentation in this question is a bit off but it's fine in the script)

    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()
有帮助吗?

解决方案

Instead of:

def loop_thru_cpus():
   for i in cpuStats:
     cpuStats = cpuStats[i]
     cpuStats = json.dumps(cpuStats._asdict())   
     ...  
     i = i+1

Try:

def loop_thru_cpus():
   for stat in cpuStats:
       stat = json.dumps(stat._asdict())     

When you say

for i in cpuStats:

i takes on values from cpuStats. i is not an integer in this case. So i = i+1 makes no sense.


cpuStats = cpuStats[i]

This probably raised an IndexError (since i is not an integer), but for some reason you are not seeing the exception that was raised.

Also note that you are redefining cpuStats here, which is probably not what you want to do.


You probably do have indentation errors in your code. Running the code you posted through cat -A shows tabs (indicated below by ^I):

             try:$
^I        $
                 command = 'put cpu.usr ' + str(currentTime) + " " + str(cpuStats[0]) + "host ="+  thisClient+ "/n"$
...
                 params = urllib.urlencode({'cpuStats': cpuStats, 'thisClient': 1234})$
...
^I         print response.status, response.reason$
$
^I    except IndexError:$
                break$

You can not mix tabs and spaces an indentation in Python code. Either use one or the other. The PEP8 style guide (and most code you see on the net) uses 4 spaces. Mixing tabs and spaces usually results in an IndentationError, but sometimes you don't get an error and just code that behaves in unexpected ways. So (if using the 4-spaces convention) be careful to use an editor that adds 4 spaces when the tab key is pressed.

Since you are not seeing the IndexError, you may not be seeing the IndentationError that should have been occurred either. How exactly are you running the problem?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top