标签:
使用with打开文件的方式,是调用了上下文管理的功能
1 #打开文件的两种方法: 2 3 f = open(‘a.txt‘,‘r‘) 4 5 with open(‘a.txt‘,‘r‘) as f 6 7 实现使用with关闭socket 8 import contextlib 9 import socket 10 11 @contextlib.contextmanage 12 def Sock(ip,port): 13 socket = socket.socket() 14 socket.bind((ip,port)) 15 socket.listen(5) 16 try: 17 yield socket 18 finally: 19 socket.close() 20 21 #执行Sock函数传入参数,执行到yield socket返回值给s,执行with语句体,执行finally后面的语句 22 with Sock(‘127.0.0.1‘,8000) as s: 23 print(s)
class RedisHelper: def __init__(self): #调用类时自动连接redis self.__conn = redis.Redis(host=‘192.168.1.100‘) def public(self, msg, chan): self.__conn.publish(chan, msg) return True def subscribe(self, chan): pub = self.__conn.pubsub() pub.subscribe(chan) pub.parse_response() return pub #订阅者 import s3 obj = s3.RedisHelper() data = obj.subscribe(‘fm111.7‘) print(data.parse_response()) #发布者 import s3 obj = s3.RedisHelper() obj.public(‘alex db‘, ‘fm111.7‘)
标签:
原文地址:http://www.cnblogs.com/liguangxu/p/5704390.html