[英]python global variable is not saved global
NexusConnectedClients = []
class Thread1(NexusCore.Thread):
def Run():
global NexusConnectedClients
if(IncomingCommand == "ADDCLIENT"):
NewClientOBJ = [
LastCID,
ClientType,
ClientADDR,
ClientObject,
Args[1],
Args[2],
'{"events":[]}'
]
NexusConnectedClients.append(NewClientOBJ)
elif(IncomingCommand == "LISTCLIENTS"):
SendResponse(NexusConnectedClients)
When i add an client, it is ok. 当我添加一个客户端时,就可以了。 When i read the
NexusConnectedClients
variable, it is add to the list. 当我读取
NexusConnectedClients
变量时,它将添加到列表中。 But when i run the LISTCLIENTS function, the list is empty. 但是,当我运行LISTCLIENTS函数时,列表为空。 What is wrong?
怎么了?
I Simplified the code a bit. 我简化了代码。 all the variables are set and all other global variables work as they should.
所有变量均已设置,所有其他全局变量均应正常工作。
EDIT I found the mistake, nothing wrong with this code but another function deleted the element from the NexusConnectedClients
array 编辑我发现了错误,此代码没有错,但是另一个函数从
NexusConnectedClients
数组中删除了该元素
You don't need to declare NexusConnectedClients
as global since it is visible in the run
method. 您无需将
NexusConnectedClients
声明为全局,因为它在run
方法中可见。 A variable must be declared global when you want to (re)bind a name in the global scope. 要在全局范围内(重新)绑定名称时,必须将变量声明为全局变量。 When a variable is modifiable, and lists are, just modify it.
当变量是可修改的并且列表是可修改的时,只需对其进行修改。
Instead what you have to do is to regulate the access to the NexusConnectedClients
. 相反,您要做的就是调节对
NexusConnectedClients
的访问。 You are modifying a shared variable inside a thread, maybe more than one. 您正在一个线程内修改一个共享变量,可能不止一个。 Use a lock.
使用锁。 Said that, I think nothing more could be said in a such small snippet.
话虽如此,我认为在这么小的片段中再也说不了什么。
Solved the problem. 解决了问题。 Didn't remove an line of code from previous testing.
没有从以前的测试中删除一行代码。 That line resetted the array
那条线重置了数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.