我试图在Python中访问函数外部的本地函数变量.所以,例如,
bye = ''
def hi():
global bye
something
something
bye = 5
sigh = 10
hi()
print bye
Run Code Online (Sandbox Code Playgroud)
以上工作正常.由于我想知道我是否可以bye
在hi()
不使用的情况下访问外部global bye
,我试过:
def hi():
something
something
bye = 5
sigh = 10
return
hi()
x = hi()
print x.bye
Run Code Online (Sandbox Code Playgroud)
以上给出AttributeError: 'NoneType' object has no attribute 'bye'
.
然后,我试过:
def hi():
something
something
bye = 5
sigh = 10
return bye
hi()
x = hi()
print x.bye
Run Code Online (Sandbox Code Playgroud)
这次它甚至没有出错.
那么,有没有办法在不使用全局变量的情况下访问函数(bye
)之外的本地函数变量()hi()
而不打印变量sigh
?(问题编辑后包括 …
我正在尝试使用namedtuple将Python对象序列化为JSON.但是我得到了这个错误.谷歌没有帮助.
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)
Run Code Online (Sandbox Code Playgroud) 如果这个问题已经在这里探讨过,请提前道歉 - 我在这里看了不同的答案,却找不到我需要的东西.
我的目标是创建一个这样的字典 - {'a':[10, 9, 10, 10], 'b':[10, 9, 1, 0], 'c':[0, 5, 0, 1], and so on}
我所拥有的是具有重复键的多个词典(每个其他词典中都有相同的键),就像这样
{'a':10, 'b': 0, 'c': 2}
{'a':7, 'b': 4, 'c': 4}
{'a':4, 'b': 5, 'c': 3}
我无法知道这些字典的数量,或者是否有密钥继续到'f',或者其中有'g',但我知道密钥是重复的.我试过defaultdict
但我得到的是 -
defaultdict(<type 'list'>, {'a': [10]})
defaultdict(<type 'list'>, {'a': [10], 'b': [3]})
defaultdict(<type 'list'>, {'a': [10], 'b': [3], 'c': [0]})
Run Code Online (Sandbox Code Playgroud)
然后为下一个字典做同样的事情 -
defaultdict(<type 'list'>, {'a': [4]})
defaultdict(<type 'list'>, {'a': [4], 'b': [5]})
defaultdict(<type 'list'>, {'a': [4], 'b': [5], 'c': [1]})
Run Code Online (Sandbox Code Playgroud)
我对上面输出的代码是 …
不同的问题:1 脚本。我必须从将在客户端运行并在远程 URL 上执行 POST 的 Python 脚本进行 JSON-ify。我正在关注这里的文档http://docs.python.org/2/library/httplib.html - 但是,我不确定我是否做得对。当我在 Mac 上运行它时,我也没有得到任何响应状态。现在,我对以下内容存有疑问——
(1) The dummy 'device_key' (of the client)
(2) The IP, Port listed at HTTPConnection --- I don't want to hard-code the IP, Port - should I be using "ServerHost:Port"
(3) The cpuStats is a nametuple (of 'user'= somevalue, 'idle' = somevalue, etc.) that is converted to a dict by _asdict(). I want to just send the cpuStats (namedtuple) to the URLpage.
(4) The cpu_times_percent(percpu=True) is what …
Run Code Online (Sandbox Code Playgroud) python ×4
json ×2
arguments ×1
defaultdict ×1
dictionary ×1
duplicates ×1
http ×1
httplib ×1
key ×1
namedtuple ×1
post ×1