Unable to stop the program the first time I press `Ctrl + C`

眉间皱痕 提交于 2019-12-11 17:07:50

问题


I have a tcp receiver which is listening for incoming images. I also have a foo() def that runs simultaneously and prints the current time every 5 seconds.

Here is the code:

from __future__ import print_function
import socket
from struct import unpack
import Queue
from PIL import Image


HOST = '10.0.0.1'
PORT = 5005
BUFSIZE = 4096
q = Queue.Queue()

class Receiver:
    ''' Buffer binary data from socket conn '''
    def __init__(self, conn):
        self.conn = conn
        self.buff = bytearray()

    def get(self, size):
        ''' Get size bytes from the buffer, reading
            from conn when necessary 
        '''
        while len(self.buff) < size:
            data = self.conn.recv(BUFSIZE)
            if not data:
                break
            self.buff.extend(data)
        # Extract the desired bytes
        result = self.buff[:size]
        # and remove them from the buffer
        del self.buff[:size]
        return bytes(result)

    def save(self, fname):
        ''' Save the remaining bytes to file fname '''
        with open(fname, 'wb') as f:
            if self.buff:
                f.write(bytes(self.buff))
            while True:
                data = self.conn.recv(BUFSIZE)
                if not data:
                    break
                f.write(data)

import time, threading
def foo():
    try:
        print(time.ctime())
        threading.Timer(5, foo).start()
    except KeyboardInterrupt:
        print('\nClosing')

def main():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    try:
        sock.bind((HOST, PORT))
    except socket.error as err:
        print('Bind failed', err)
        return
    sock.listen(1)
    print('Socket now listening at', HOST, PORT)
    try:
        while True:
            conn, addr = sock.accept()
            print('Connected with', *addr)
            # Create a buffer for this connection
            receiver = Receiver(conn)
            # Get the length of the file name
            name_size = unpack('B', receiver.get(1))[0] 
            # Get the file name itself
            name = receiver.get(name_size).decode()
            q.put(name)
            print('name', name)
            # Save the file
            receiver.save(name)
            conn.close()
            print('saved\n')

    # Hit Break / Ctrl-C to exit
    except KeyboardInterrupt:
        print('\nClosing')

    sock.close()

if __name__ == '__main__':
    foo()
    main()

The problem is that when I press Ctrl + C buttons in order to terminate the program, the first time it prints "closing" but it isn't terminated and I should press these buttons at least two times.

How can I stop the program the first time I press Ctrl + C? I removed try and except in def foo(), but it didn't change the result.


回答1:


Just reraise the exception after the print statement:

except KeyboardInterrupt:
    print('\nClosing') 
    raise


来源:https://stackoverflow.com/questions/53123454/unable-to-stop-the-program-the-first-time-i-press-ctrl-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!