使用特定按键中断 Python 中的 recvfrom() 调用

问题描述 投票:0回答:0

我在 Python 中有一个 while 循环调用一个函数,该函数期望通过 recvfrom() 调用从 UDP 客户端接收消息。

我想知道是否可以使用例如“+”键来中断消息接收过程。 按下此键后,应用程序可以允许其他选项,例如发送消息。

不知道这是否可以在不使用线程的情况下完成。

我正在使用 Python 3.10.6 和 Linux

import socket
import sys

# Parse app checker
if len(sys.argv) == 3:
    # Get "IP address of Server" and also the "port number" from argument 1 and argument 2
    ip = sys.argv[1]
    port = int(sys.argv[2])
else:
    print("Run like : python3 server.py <arg1:server ip:this system IP 192.168.1.6> <arg2:server port:4444 >")
    exit(1)

# Create a UDP socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Bind the socket to the port
server_address = (ip, port)
s.bind(server_address)

def fun_recv_data():
    global address
    data, address = s.recvfrom(4096)
    print (data)

while True:
    # Receive data
    fun_recv_data()
python while-loop key interrupt
© www.soinside.com 2019 - 2024. All rights reserved.