Actual case :
We have achieved a telnet client TelnetClient, Of the calling instance start() Method to start the interaction between client and server , After the interaction, you need to call cleanup() Method , Close the connected socket, And write the operation history to a file and close it .
Can you make TelnetClient The instance of supports the context management protocol , Instead of manually calling cleanup() Method .
Solution :
Implement the context management protocol , To define an instance __enter__,__exit__ Method , They are in with Called at the beginning and end .
(1) Examples of context management
'''
Context management is often used when operating on files with sentence ,
The benefit of using context management is to with Not displayed after the end of the statement close To close a file ,
Such a cleanup is left to the context management protocol , Let them automatically help us complete .
'''
with open('demo.txt', 'w') as f:
f.write('abcdef')
f.writelines(['xyz\n', '123\n'])
# f.close()
(2) Implement a class object to support the context management protocol
from telnetlib import Telnet
from sys import stdin, stdout
from collections import deque
class TelnetClient(object):
def __init__(self, addr, port=23):
self.addr = addr
self.port = port
self.tn = None
def start(self):
# A human display throws an exception , To prove that even if there is an anomaly __exit__ Will also be called
# raise Exception('Test')
# Enter the user name and password
# user
t = self.tn.read_until(b'login: ')
stdout.write(t)
user = stdin.readline()
self.tn.write(user)
# password
t = self.tn.read_until(b'password: ')
if t.startswith(user[:-1]):
t = t[len(user) + 1:]
stdout.write(t)
self.tn.write(stdin.readline())
# Log in to the server's shell among
t = self.tn.read_until('$ ')
stdout.write(t)
while True:
uinput = stdin.readline()
if not uinput:
break
self.history.append(uinput)
self.tn.write(uinput)
t = self.tn.read_until('$ ')
stdout.write(t[len(uinput) + 1:])
def cleanup(self):
pass
def __enter__(self):
# Telnet Connection object
self.tn = Telnet(self.addr, self.port)
# Create a queue to store the user's operation history
self.history = deque()
# __enter__() What is returned is with in as The object of ,self Oneself
return self
# 3 The parameters are exception types 、 outliers 、 Trace stack information
# In the case of no exceptions, the three parameters are None
def __exit__(self, exc_type, exc_val, exc_tb):
# print('In __exit__')
# Close the server connection socket
self.tn.close()
self.tn = None
with open(self.addr + 'history.txt', 'w') as f:
f.writelines(self.history)
# Default return None
# return True # Don't throw exceptions
with TelnetClient('127.0.0.1') as client:
client.start()
print('END')
Python常用的數據結構,有如下幾種.但是我們用的最多的,
Recently, I received a network
Python describe LeetCode 82. D