1

I'm using telnetlib to communicate with some equipment which has Telnet implemented as single user. 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:

 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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
flamenco
  • 2,702
  • 5
  • 30
  • 46
  • 1
    Why test both locals and globals? You make it clear `tn` is a global with the `global tn` line. And define *does not work*? Why not just rebind `tn` to `None` instead? – Martijn Pieters Sep 22 '14 at 16:25

1 Answers1

2

Don't delete, rebind. Start with tn set to 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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 1
    1. Sounds good but if we have `tn=None`, the script will never exectute `tn.close()`. 2. What line should be `global tn`? – flamenco Sep 23 '14 at 03:23
  • 1
    @flamenco: if `tn` is `None`, there is *nothing **to** close*. It doesn't matter what line `global tn` is on; it applies to the whole function it is in. As such it makes sense to list it first, for readability. – Martijn Pieters Sep 23 '14 at 06:42