Namedtuple error [closed]

孤人 提交于 2019-12-24 01:44:47

问题


I am trying to serialize a Python object into JSON using namedtuple. But I get this error. Google does not help.

Traceback (most recent call last):
 File "cpu2.py", line 28, in <module>
 cpuInfo = collections.namedtuple('cpuStats',('cpu.usr', ('str(currentTime) + " " 
 +str(cpuStats[0]) + " host="+ thisClient')), ('cpu.nice', ('str(currentTime) + " " 
 +str(cpuStats[1]) + " host="+ thisClient')), ('cpu.sys',('str(currentTime) + " " 
 +str(cpuStats[2]) + " host="+ thisClient')), ('cpu.idle',('str(currentTime) + " " 
 +str(cpuStats[3]) + " host="+ thisClient')))
 TypeError: namedtuple() takes at most 4 arguments (5 given)

回答1:


Here is a link to the documentation for namedtuple. You aren't initializing it properly.

How I'm guessing you should initialize it:

cpuInfo = collections.namedtuple('cpuStats', ['usr', 'nice', 'sys', 'idle'])

# In this case, usr=str(currentTime) + " " +str(cpuStats[0]) + " host=" + thisClient
# You can figure the rest out...
info = cpuInfo(usr='fill',
               nice='this',
               sys='your',
               idle='self')

Also, you might want to read this question which talks about serializing namedtuples in json.



来源:https://stackoverflow.com/questions/18707277/namedtuple-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!