Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python can';t关闭键盘上的插座中断_Python_Sockets - Fatal编程技术网

Python can';t关闭键盘上的插座中断

Python can';t关闭键盘上的插座中断,python,sockets,Python,Sockets,所以我试着把我的头绕在插座上,并有一个非常简单的脚本 但是由于某种原因,我不能用键盘中断来终止这个脚本 如何使用键盘中断来终止脚本,为什么不能使用键盘中断来终止脚本 要中断以退出while循环。如果没有中断,循环将不会结束 为了安全起见,请检查是否设置了连接 从套接字导入套接字、AF\u INET、SOCK\u流 sock=套接字(AF\u INET,sock\u STREAM) sock.bind((“localhost”,7777)) 短袜,听(1) 尽管如此: connection=No

所以我试着把我的头绕在插座上,并有一个非常简单的脚本 但是由于某种原因,我不能用键盘中断来终止这个脚本

如何使用
键盘中断来终止脚本,为什么不能使用
键盘中断来终止脚本

  • 中断
    以退出
    while
    循环。如果没有
    中断
    ,循环将不会结束
  • 为了安全起见,请检查是否设置了连接

  • 从套接字导入套接字、AF\u INET、SOCK\u流
    sock=套接字(AF\u INET,sock\u STREAM)
    sock.bind((“localhost”,7777))
    短袜,听(1)
    尽管如此:
    
    connection=None#尝试向套接字添加超时,如下所示:

    from socket import socket, AF_INET, SOCK_STREAM
    
    sock = socket(AF_INET, SOCK_STREAM)
    sock.bind(("localhost", 7777))
    sock.listen(1)
    while True:
        connection = None # <---
        try:
            connection, address = sock.accept()
            print("connected from ", address)
            received_message = connection.recv(300)
            if not received_message:
                break
            connection.sendall(b"hello")
        except KeyboardInterrupt:
            if connection:  # <---
                connection.close()
            break  # <---
    

    我在Windows上遇到了这个问题。以下是我如何处理停止进程的问题:

    from socket import socket, AF_INET, SOCK_STREAM
    sock = socket(AF_INET, SOCK_STREAM)
    sock.bind(("localhost", 7777))
    sock.settimeout(1.0)
    sock.listen(1)
    while True:
        try:
            connection, address = sock.accept()
            print("connected from " + address)
            received_message = sock.recv(300)
            if not received_message:
                break
            connection.sendall(b"hello")
        except IOError as msg:
            print(msg)
            continue    
        except KeyboardInterrupt:
            try:
                if connection:
                    connection.close()
            except: pass
            break
    sock.shutdown
    sock.close()
    
    请注意,要触发键盘中断异常,请使用:

    Ctrl
    +
    Fn
    +
    PageUp(暂停/中断)

    对于windows用户

    上述试图捕捉键盘中断的解决方案似乎不起作用。我最后在我的插座上设置了一个超时

    比如:
    server\u socket.settimeout(10)


    此处,在10秒的不活动(如10秒内未接收任何内容)后引发异常。

    如果远端很少发送数据,您也应该为连接设置超时。 在这种情况下,当可以检查
    键盘中断时,连接将引发超时异常

    从套接字导入套接字、AF\u INET、SOCK\u流
    sock=套接字(AF\u INET,sock\u STREAM)
    sock.bind((“localhost”,7777))
    sock.settimeout(1.0)
    短袜,听(1)
    尽管如此:
    尝试:
    连接,地址=sock.accept()
    connection.settimeout(1.0)
    打印(“连接自”+地址)
    已接收消息=sock.recv(300)
    如果未收到信息:
    打破
    connection.sendall(b“你好”)
    除socket.timeout外:
    持续
    除了IOError作为msg:
    打印(msg)
    持续
    除键盘中断外:
    尝试:
    如果连接:
    连接。关闭()
    除了:通过
    打破
    短袜关闭
    sock.close()
    
    尝试使用
    超时
    使程序周期性地从
    接受
    等待过程中“跳出”以接收键盘中断命令

    下面是套接字服务器的一个示例:

        try:
            while self.running:
                try:
                    c, addr = self.socket.accept()
                    print("Connection accepted from " + repr(addr[1]))
                    # do special stuff here...
                    print("sending...")
                    continue
                except (SystemExit, KeyboardInterrupt):
                    print("Exiting....")
                    service.stop_service()
                    break
                except Exception as ex:
                    print("======> Fatal Error....\n" + str(ex))
                    print(traceback.format_exc())
                    self.running = False
                    service.stop_service()
                    raise
        except (SystemExit, KeyboardInterrupt):
            print("Force Exiting....")
            service.stop_service()
            raise
    
    def stop_service(self):
        """
        properly kills the process: https://stackoverflow.com/a/16736227/4225229
        """
        self.running = False
        socket.socket(socket.AF_INET,
                      socket.SOCK_STREAM).connect((self.hostname, self.port))
        self.socket.close()
    

    CTRL+C事件可以在单独的进程中捕获,并发送回主进程中运行的另一个线程以终止套接字。下面的示例使用Python 3.5.4在Windows 10上成功测试。在周围放置一些注释和打印语句,以便您可以看到发生了什么

    从多处理导入管道,处理
    从套接字导入套接字、AF\u INET、SOCK\u流
    从线程导入线程
    导入时间
    def检测_中断(连接):
    尝试:
    打印(“监听键盘中断…”)
    尽管如此:
    时间。睡眠(1)
    除键盘中断外:
    打印(“检测到键盘中断!”)
    打印(“发送IPC…”)
    conn.send(正确)
    康涅狄格州关闭
    def侦听中断(conn,sock):
    打印(“侦听IPC…”)
    康涅狄格州
    打印(“检测到IPC!”)
    打印(“收尾袜…”)
    sock.close()
    如果名称=“\uuuuu main\uuuuuuuu”:
    sock=套接字(AF\u INET,sock\u STREAM)
    sock.bind((“localhost”,7777))
    短袜,听(1)
    #将管道装入板条箱,用于进程间通信
    主接头,检测接头=管道()
    #在主进程中创建线程以侦听连接
    收听\u中断\u线程=线程(
    目标=侦听\u中断,args=(主\u连接,sock),守护进程=真
    侦听线程的中断。开始()
    #创建一个单独的进程来检测键盘中断
    检测中断进程=进程(
    目标=检测中断,参数=(检测连接)
    检测\u中断\u进程。启动()
    连接=无
    尝试:
    尽管如此:
    打印(“运行套接字接受()”)
    连接,地址=sock.accept()
    打印(“连接自”+地址)
    已接收消息=sock.recv(300)
    如果未收到信息:
    打破
    connection.sendall(b“你好”)
    除键盘中断外:
    打印(“处理键盘中断”)
    sock.close()
    如果连接:
    连接。关闭()
    
    这很奇怪,因为。运行此命令仍然无法使用
    CTRL-C
    关闭脚本,因为我在windows上使用此命令。这就是键盘中断未被触发的原因吗?@Zion,我在Linux上尝试过,它成功了@锡安,按住Ctrl键怎么样?
    +
    Break
    ?谢谢你,伙计。我猜这是窗户的东西。我在OS X上试过了,效果很好。如果我在windows上做这件事会有不同,因为在mac上做这件事会捕获键盘中断?我不能告诉你,因为我在Linux上,试试看:)你也可以将它用于仅发送设置(即不做任何
    sock.recv()
    ,因为你使用的是TCP,本质上是UDP)通过使用与
    除外套接字匹配的
    尝试
    。超时:仅围绕
    sock.accept()
    行继续
    ,然后使用
    除外键盘中断:
    外部块。
        try:
            while self.running:
                try:
                    c, addr = self.socket.accept()
                    print("Connection accepted from " + repr(addr[1]))
                    # do special stuff here...
                    print("sending...")
                    continue
                except (SystemExit, KeyboardInterrupt):
                    print("Exiting....")
                    service.stop_service()
                    break
                except Exception as ex:
                    print("======> Fatal Error....\n" + str(ex))
                    print(traceback.format_exc())
                    self.running = False
                    service.stop_service()
                    raise
        except (SystemExit, KeyboardInterrupt):
            print("Force Exiting....")
            service.stop_service()
            raise
    
    def stop_service(self):
        """
        properly kills the process: https://stackoverflow.com/a/16736227/4225229
        """
        self.running = False
        socket.socket(socket.AF_INET,
                      socket.SOCK_STREAM).connect((self.hostname, self.port))
        self.socket.close()
    
    import socket
    
    host = "127.0.0.1"
    port = 23333
    
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
    sock.bind((host,port))
    sock.listen()
    
    sock.settimeout(0.5)
    
    print("> Listening {}:{} ...".format(host,port))
    
    try:
        while True:
            try:
                conn, addr = sock.accept()
                data = conn.recv(1024)
                if not data:
                    print("x Client disconnected!")
                    break
                else:
                    print("> Message from client: {}".format(data.decode()))
                    msg = "> Message from server".format(data.decode()).encode()
                    conn.sendall(msg)
            except socket.timeout:
                print("Timeout")
            except KeyboardInterrupt:
                pass
    except KeyboardInterrupt:
        print("Server closed with KeyboardInterrupt!")