程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Detailed explanation of Python implementation context management

編輯:Python

1、 How to make objects support context management ?

         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 .

2、 Code demonstration

(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')


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved