get-my-ip.py: Python 2.x sockets can't be used in 'with' statements
authorW. Trevor King <wking@tremily.us>
Tue, 19 Feb 2013 02:56:16 +0000 (21:56 -0500)
committerW. Trevor King <wking@tremily.us>
Mon, 21 Oct 2013 03:49:00 +0000 (20:49 -0700)
They don't have __exit__.  Use an explicit try/except block to be
compatible with both 2.x and 3.x.

setup/get-my-ip.py

index 286e67ff912e2436dfa11be29f709a2dc30b56a0..6b93ca13a65f815220771132845e228ce67835d3 100755 (executable)
@@ -7,9 +7,12 @@ import socket as _socket
 
 
 def get_my_ip(host, port=80):
-    with _socket.socket(_socket.AF_INET, _socket.SOCK_DGRAM) as s:
+    s = _socket.socket(_socket.AF_INET, _socket.SOCK_DGRAM)
+    try:
         s.connect((host, port))
         return s.getsockname()[0]
+    finally:
+        s.close()
 
 
 if __name__ == '__main__':