The ability to use with open files is called context-managed
1 #There are two ways to open a file:2 3f = open ('a.txt','R')4 5With open ('a.txt','R') as F6 7 implement use with close socket8 ImportContextlib9 ImportSocketTen One @contextlib. Contextmanage A defSock (ip,port): -Socket =Socket.socket () - Socket.bind ((ip,port)) theSocket.listen (5) - Try: - yieldSocket - finally: + socket.close () - + #Executes the sock function passed in the parameter, executes to the yield socket return value to S, executes the WITH statement body, executes the statement after finally AWith Sock ('127.0.0.1', 8000) as S: at Print(s)
Publication subscriptions for Redis
classRedishelper:def __init__(self):#automatically connect to Redis when calling classesSelf.__conn= Redis. Redis (host='192.168.1.100') defPublic (Self, MSG, chan): Self.__conn. Publish (Chan, msg)returnTruedefsubscribe (self, chan): Pub= self.__conn. PubSub () Pub.subscribe (chan) pub.parse_response ()returnPub#subscribed byImportS3obj=S3. Redishelper () Data= Obj.subscribe ('fm111.7')Print(Data.parse_response ())#published byImportS3obj=S3. Redishelper () obj.public ('Alex DB','fm111.7')
Python context Management, Redis's publish subscription