1

Given this portion of code, when pressing Ctrl+C the program returns error "name 'sock' is not defined.". I guess this is normal since sock.close() is outside the class, but what should I do to prevent it ?

In my case it is about a client, not server, that asks for socket close.

import socket

class something(object):
    def connect(self):
        self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
        self.sock.connect((self.tcp_ip, self.tcp_port))
        # etc.

if __name__ == '__main__':
    try:
        app = something()
        app.connect()
    except KeyboardInterrupt:
        pass
    finally:
        sock.close()
secarica
  • 597
  • 5
  • 18
  • 1
    possible duplicate of [How do I correctly clean up a Python object?](http://stackoverflow.com/questions/865115/how-do-i-correctly-clean-up-a-python-object) – Nicu Stiurca Aug 14 '15 at 22:05
  • 1
    `something()` in your code above will not ever create a socket at all. Is there more code you thought wasn't relevant? Please include it :). – Cyphase Aug 14 '15 at 22:12
  • @[Cyphase](http://stackoverflow.com/users/892383/cyphase) - right, there was something I missed out, thanks for pointing (I should learn to post here only after some sleep :) – secarica Aug 15 '15 at 10:59

3 Answers3

2

This should work I think

import socket
class something(object):
    def __init__(self):
        self.sock = None

    def connect(self):
        self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
        self.sock.connect(('127.0.0.1', 12397))
        self.sock.recv(1024)

    def close(self):
        self.sock.close()

if __name__ == '__main__':
    try:
        sk = something()
        sk.connect()
    except KeyboardInterrupt:
        pass
    finally:
        sk.close()
        print "Socket Closed"
Achayan
  • 5,720
  • 2
  • 39
  • 61
0

For closing nicely a connection with <ctrl+c> signal may be used to catch keyboard interrupt:

#!/usr/bin/env python3
""" testsocketclose.py """
import signal, socket, sys, time

def handler(signum, frame):
    """ Catch <ctrl+c> signal for clean stop"""
    print('\nNice exit')
    connection.close()
    sys.exit(0)

signal.signal(signal.SIGINT, handler)

connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection.bind(('localhost', 5555))
connection.listen(5)

while 1:
    print("Socket open:\n{}\nExit with <ctrl+c>".format(connection))
    time.sleep(2)
freezed
  • 1,269
  • 1
  • 17
  • 34
-1

Try this instead.

if __name__ == '__main__':
    try:
        foo = something()
        foo.connect()
    except KeyboardInterrupt:
        pass
    finally:
        foo.sock.close()
Alex Jadczak
  • 550
  • 3
  • 11
  • Unlikely as it might be in this manufactured example, this will still raise the exception if the `KeyboardInterrupt` comes before `.connect()` is called. – Cyphase Aug 14 '15 at 22:15
  • Yeah that's fair. But, using a keyboard interrupt to close out the socket probably isn't the best idea to begin with. – Alex Jadczak Aug 14 '15 at 22:18
  • It's made-up code, but I think the idea is to allow `Ctrl+C` to be used for exiting the program, or a section of it, and the OP wants the socket to be closed. I think the question would still apply for any other method of signalling. – Cyphase Aug 14 '15 at 22:21
  • When I read the OP's question I would interpret it as: How do I prevent the "name 'sock' is not defined in this code? I guess I could be misinterpreting the question though. – Alex Jadczak Aug 14 '15 at 22:32