简体   繁体   English

从locals()或globals()中查找并删除Python对象

[英]Find and remove a Python object from locals() or globals()

I'm using telnetlib to communicate with some equipment which has Telnet implemented as single user. 我正在使用telnetlib与某些已将Telnet实现为单用户的设备进行通信。 Therefore, I have to detect and remove the telnet object created from a previous attempt to establish communication.(Ex: tn = telnetlib.Telnet(HOST) ) My attempt is something like bellow but it does not work: 因此,我必须检测并删除先前尝试建立通信所创建的telnet对象。(例如: tn = telnetlib.Telnet(HOST) )我的尝试类似于下面,但它不起作用:

 if 'tn' in loccals() or 'tn' in globals():
     print "Telnet object exists. Remove it."
     tn.close()
     del tn
 else:
     print "Create a Telnet object."
     global tn
     tn = telnetlib.Telnet(HOST)

print tn

Don't delete, rebind. 不要删除,重新绑定。 Start with tn set to None : 首先将tn设置为None

tn = None

Now you can test for the value: 现在您可以测试该值:

if tn is not None:
    tn.close()
    tn = None
else:
    tn = telnetlib.Telnet(HOST)

Note that the global keyword marks a name as global in the whole scope , not just from that line onwards. 注意, global关键字将整个范围内的名称标记为全局,而不仅仅是从该行开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM