按Ctrl + C无法关闭套接字

时间:2014-11-08 16:03:48

标签: python sockets

我正在尝试在用户按下ctrl-c时关闭套接字。如果套接字仍然在做某事,这可以正常工作。但当套接字完成它的工作并且什么都不做时我按下ctrl-c没有任何反应。顺便说一句,我使用的是Windows 8.1。

这是我的代码:

# close socket ctrl-c
from signal import signal, SIGINT
def sigint_received(signum, frame):
    s.close()
    exit(0)

# register SIGINT callback
signal(SIGINT, sigint_received)

当我尝试使用此代码时,我遇到了同样的问题:

OriginalExceptHook = sys.excepthook
def NewExceptHook(type, value, traceback):
    if type == KeyboardInterrupt:
        exit("\nExiting.")
    else:
        OriginalExceptHook(type, value, traceback)
    sys.excepthook = NewExceptHook

任何人都知道什么是错的?

1 个答案:

答案 0 :(得分:1)

重新评论,使用except表示任何意外的KeyboardInterrupt都会抓住" Ctrl + C"同样,我的意思是:

while 1:
    try:
        ... your stuff here ...
        ... you should also break the while loop if no data is received ...
    # and except it when Ctrl + C like happens
    except KeyboardInterrupt:
        print "Ctrl C or alike is pressed..."