sockets - python `with .. as ..` statement and multiple return values -



sockets - python `with .. as ..` statement and multiple return values -

i trying utilize python with-statement (a.k.a. context manager) ensure tcp connection socket created server_socket.accept() closed. obvious form not work because accept() returns multiple values.

is there way utilize with-statement functions multiple homecoming values?

a minimal illustration below, want utilize commented code replace try/finally block.

#!/usr/bin/env python3 import socket socket import socket socket socket(socket.af_inet, socket.sock_stream) server_socket: server_socket.bind(('', 8011)) server_socket.listen(1) print("server ready") while true: # server_socket.accept() (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()

the error message when using commented with-statement is:

traceback (most recent phone call last): file "./test.py", line 26, in <module> server_socket.accept() (connection_socket, _): attributeerror: __exit__

presumably because tuple not have __exit__ attribute required with.

the homecoming value of socket.socket has built-in context manager implements __exit__ , __enter__. tuple returned accept not, there library add together it:

import socket import contextlib @contextlib.contextmanager def accept(s): c,a = s.accept() print('client connected on',a) yield c,a print('client disconnected on',a) c.close() socket.socket() s: s.bind(('',8000)) s.listen(1) accept(s) (c,a): while true: info = c.recv(1024) if not data: break c.sendall(data)

see:

https://docs.python.org/3.3/library/contextlib.html

p.s. without contextlib:

import socket socket.socket() s: s.bind(('',8000)) s.listen(1) s.accept()[0] c: = c.getpeername() print('client connected on',a) while true: info = c.recv(1024) if not data: break c.sendall(data) print('client disconnected on',a)

python sockets with-statement contextmanager

Comments

Popular posts from this blog

xslt - DocBook 5 to PDF transform failing with error: "fo:flow" is missing child elements. Required content model: marker* -

mediawiki - How do I insert tables inside infoboxes on Wikia pages? -

Local Service User Logged into Windows -