1

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()
2
  • 1
    1. except block don't match indentation of try block, 2. loop_thru_cpus is never called 3. You call request method on some conn object, but as far as I can tell it is not defined. 4. Remove trailing spaces.
    – zero323
    Sep 10, 2013 at 22:13
  • Thx so much :) I have added the current response on running it in comment to the answer by unutbu.
    – askance
    Sep 10, 2013 at 22:32

1 Answer 1

1

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?

3
  • Thx so much! You guys are awesome! The indentation here was unformatted and the suggestions by you and zero323 worked (as far as I can tell) - The indexing was the main issue. On running it now I get - a '200 OK' for all 4 cpus in my machine. 1 question though - Is there any way to check with Bash if the data posted on the server?
    – askance
    Sep 10, 2013 at 22:34
  • I don't know a better alternative than downloading the data.
    – unutbu
    Sep 11, 2013 at 2:03
  • That's ok. I'll get to know from the project architect soon anyways.
    – askance
    Sep 11, 2013 at 2:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.