Python - Не могу убить основной поток с KeyboardInterrupt

Я делаю простой многопоточный сканер портов. Он сканирует все порты на хосте и возвращает открытые порты. Проблема заключается в прерывании сканирования. Завершение сканирования занимает много времени, и иногда я хочу убить программу с помощью C-c, находясь в середине сканирования. Проблема в том, что сканирование выигралоне останавливайся Основной поток заблокирован в queue.join () и не обращает внимания на KeyboardInterrupt до тех пор, пока все данные из очереди не будут обработаны, что приведет к удалению основного потока и корректному выходу из программы. Все мои потоки демонизированы, поэтому, когда основной поток умирает, они должны умереть вместе с ним.

Я пытался использовать сигнал lib, безуспешно. Переопределение потоков. Класс класса и добавление метода для корректного завершеният работа ... Основной поток только что выигралполучить KeyboardInterrupt во время выполнения queue.join ()

import threading, sys, Queue, socket

queue = Queue.Queue()

def scan(host):
    while True:
        port = queue.get()

        if port > 999 and port % 1000 == 0:
            print port
        try:
            #sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            #sock.settimeout(2) #you need timeout or else it will try to connect forever! 
            #sock.connect((host, port))
            #----OR----
            sock = socket.create_connection((host, port), timeout = 2)

            sock.send('aaa')
            data = sock.recv(100)
            print "Port {} open, message: {}".format(port, data)
            sock.shutdown()
            sock.close()
            queue.task_done()
        except:
            queue.task_done()


def main(host):
    #populate queue
    for i in range(1, 65536):
        queue.put(i)
    #spawn worker threads
    for port in range(100):
        t = threading.Thread(target = scan, args = (host,))
        t.daemon = True
        t.start()

if __name__ == '__main__':
    host = ""

    #does input exist?
    try:
        host = sys.argv[1]
    except:
        print "No argument was recivied!"
        exit(1)

    #is input sane?
    try:
        host = socket.gethostbyname(host)
    except:
        print "Adress does not exist"
        exit(2)

    #execute main program and wait for scan to complete
    main(host)
    print "Post main() call!"
    try:
        queue.join()
    except KeyboardInterrupt:
        print "C-C"
        exit(3)

РЕДАКТИРОВАТЬ:

Я нашел решение с помощью модуля времени.

#execute main program and wait for scan to complete
main(host)

#a little trick. queue.join() makes main thread immune to keyboardinterrupt. So use queue.empty() with time.sleep()
#queue.empty() is "unreliable" so it may return True a bit earlier then intented.
#when queue is true, queue.join() is executed, to confirm that all data was processed.
#not a true solution, you can't interrupt main thread near the end of scan (when queue.empty() returns True)
try:
    while True:
        if queue.empty() == False:
            time.sleep(1)
        else:
            break
except KeyboardInterrupt:
    print "Alas poor port scanner..."
    exit(1)
queue.join()

Ответы на вопрос(2)

Ваш ответ на вопрос