【问题标题】:Unable to stop the program the first time I press `Ctrl + C`第一次按“Ctrl + C”时无法停止程序
【发布时间】:2018-11-03 02:22:15
【问题描述】:

我有一个正在监听传入图像的 tcp 接收器。我还有一个同时运行的 foo() def,它每 5 秒打印一次当前时间。

代码如下:

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()

问题是当我按下Ctrl + C 按钮以终止程序时,它第一次打印“关闭”但它没有终止,我应该至少按下这些按钮两次。

如何在第一次按Ctrl + C 时停止程序?我在 def foo() 中删除了 tryexcept,但它并没有改变结果。

【问题讨论】:

    标签: python terminate


    【解决方案1】:

    只需在 print 语句后重新引发异常:

    except KeyboardInterrupt:
        print('\nClosing') 
        raise
    

    【讨论】:

    • 谢谢,但在哪个例外之后? (有两个,一个在def main(),另一个在def foo())。我应该在 def foo() 中删除 tryexcept 吗?
    • @helen 如果你想让任何 ctrl+c 中断你的程序,你应该把它添加到两者中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-10
    • 1970-01-01
    • 1970-01-01
    • 2016-03-05
    • 2018-06-23
    • 2011-08-29
    相关资源
    最近更新 更多