【问题标题】:Python JSON try except block not workingPython JSON尝试除了块不起作用
【发布时间】:2013-09-10 21:55:02
【问题描述】:

多次尝试后,此代码仍然失败。我想要做的是将“cpu stats”作为 JSON 发送到服务器。问题是,单独的 cpustats 很好 - 只有 1 个具有不同 cpupercentages 的命名元组 - 用户、空闲等。但是“percpu”返回每个 cpu 的命名元组(用户、空闲等)的列表。所以我无法将列表转换为字典。我正在尝试遍历列表,然后将每个 namedtuple 发送到服务器。 (供参考 - 我使用的是 2.7.5)。该脚本运行良好,无需尝试循环和尝试/除 - 它返回“200 OK”。但是现在当我运行它时,它甚至不会返回错误,任何响应消息/状态。就好像脚本只是绕过了整个 try/except 块。只是最后的“打印 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()

【问题讨论】:

  • 1.除了块与 try 块的缩进不匹配, 2. loop_thru_cpus 永远不会被调用 3. 你在一些 conn 对象上调用 request 方法,但据我所知它没有定义。 4.删除尾随空格。
  • 非常感谢 :) 我已经在 unutbu 的回答中添加了运行它的当前响应。

标签: python json for-loop exception-handling try-except


【解决方案1】:

代替:

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

试试:

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

当你说

for i in cpuStats:

i 采用来自cpuStats 的值。在这种情况下,i 不是整数。所以i = i+1 没有意义。


cpuStats = cpuStats[i]

这可能引发了 IndexError(因为 i 不是整数),但由于某种原因,您没有看到引发的异常。

另请注意,您在这里重新定义了cpuStats,这可能不是您想要做的。


您可能确实在您的代码中存在缩进错误。运行您通过cat -A 发布的代码会显示选项卡(下面由^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$

您不能在 Python 代码中混合使用制表符和空格以及缩进。使用其中一种。 PEP8 样式指南(以及您在网上看到的大多数代码)使用 4 个空格。混合制表符和空格通常会导致 IndentationError,但有时您不会收到错误,而只是代码以意想不到的方式运行。所以(如果使用 4 个空格的约定)请小心使用在按下 tab 键时添加 4 个空格的编辑器。

由于您没有看到 IndexError,您可能也没有看到本应发生的 IndentationError。你究竟是如何解决这个问题的?

【讨论】:

  • 非常感谢!你们真棒!此处的缩进未格式化,您和 zero323 的建议有效(据我所知) - 索引是主要问题。现在运行它,我得到 - 我机器中所有 4 个 CPU 的“200 OK”。 1 个问题 - 如果数据发布在服务器上,有什么方法可以检查 Bash?
  • 我不知道比下载数据更好的选择。
  • 没关系。无论如何,我很快就会从项目架构师那里了解情况。
猜你喜欢
  • 2018-02-11
  • 1970-01-01
  • 2019-01-29
  • 1970-01-01
  • 1970-01-01
  • 2014-02-19
  • 1970-01-01
  • 2021-09-22
  • 1970-01-01
相关资源
最近更新 更多