gpt4 book ai didi

python `with .. as ..`语句和多个返回值

转载 作者:行者123 更新时间:2023-11-28 20:44:28 28 4
gpt4 key购买 nike

我正在尝试使用 python with-statement(又名上下文管理器)来确保 server_socket.accept() 创建的 TCP 连接套接字始终关闭。然而,明显的形式不起作用,因为 accept() 返回多个值。

有没有办法对具有多个返回值的函数使用 with 语句?

下面是一个最小的例子,我想使用类似注释代码的东西来替换 try/finally block 。

#!/usr/bin/env python3

import socket
from socket import socket as Socket

with Socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:

server_socket.bind(('', 8011))
server_socket.listen(1)
print("server ready")

while True:

# with server_socket.accept() as (connection_socket, _):
# request = connection_socket.recv(1024).decode('ascii')
# reply = request.upper()
# connection_socket.send(reply.encode('ascii'))

try:
connection_socket, _ = server_socket.accept()
request = connection_socket.recv(1024).decode('ascii')
reply = request.upper()
connection_socket.send(reply.encode('ascii'))

finally:
connection_socket.close()

使用带注释的 with 语句时的错误信息是:

Traceback (most recent call last):
File "./test.py", line 26, in <module>
with server_socket.accept() as (connection_socket, _):
AttributeError: __exit__

大概这是因为元组没有 with 所需的 __exit__ 属性。

最佳答案

socket.socket 的返回值有一个内置的上下文管理器,它实现了__exit____enter__accept 返回的元组没有,但您可以从元组中分离出客户端套接字和地址,并单独在客户端套接字上使用 with:

import socket

with socket.socket() as s:
s.bind(('',8000))
s.listen(1)
c,a = s.accept(s)
with c:
while True:
data = c.recv(1024)
if not data: break
c.sendall(data)

关于python `with .. as ..`语句和多个返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26313182/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com