吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 310|回复: 0
收起左侧

[求助] 关于多线程的程序如何在主线程中捕获键盘中断信号

[复制链接]
sweetarea 发表于 2024-3-29 14:55
大家好,我学习异步编程的时候,遇到下面的这段代码:
[Python] 纯文本查看 复制代码
from threading import Thread
import socket


class ClientEchoThread(Thread):

    def __init__(self, client):
        super().__init__()
        self.client = client

    def run(self):
        try:
            while True:
                data = self.client.recv(2048)
                if not data: #A
                    raise BrokenPipeError('Connection closed!')
                print(f'Received {data}, sending!')
                self.client.sendall(data)
        except OSError as e: #B
            print(f'Thread interrupted by {e} exception, shutting down!')

    def close(self):
        if self.is_alive(): #C
            self.client.sendall(bytes('Shutting down!', encoding='utf-8'))
            self.client.shutdown(socket.SHUT_RDWR) #D


with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(('127.0.0.1', 8000))
    server.listen()
    connection_threads = []
    try:
        while True:
            connection, addr = server.accept()
            thread = ClientEchoThread(connection)
            connection_threads.append(thread)
            thread.start()
    except KeyboardInterrupt:
        print('Shutting down!')
        [thread.close() for thread in connection_threads] #E

当运行环境是windows,在cmd中python 运行它,启动后在命令行中无法输入CTRL+C。


但是如果换成下面的代码就可以正常捕获键盘中断信号。
[Python] 纯文本查看 复制代码
import time


def main():
    print('before ...')
    time.sleep(20)
    print('after ...')


if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print('\nKeyboardInterrupt ...')
    print('the end')

请问为什么第一段程序无法捕捉到键盘中断信号CTRL+C了?该如何改写在 try 中的循环中能触发 KeyboardInterrupt 了?

无法中断

无法中断

键盘中断信号成功

键盘中断信号成功

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-11-24 16:37

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表