码迷,mamicode.com
首页 > 编程语言 > 详细

Python 上下文关系

时间:2016-09-16 11:18:51      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

import socket
import contextlib

@contextlib.contextmanager
def con(host,port):
    sk = socket.socket()
    sk.bind((host,port))
    sk.listen(5)
    try:
        print ("auto connect")
        yield
        print ("============")
    finally:
        print ("finally close")
        sk.close()


with con(127.0.0.1,8888) as sock:
    print ("sock auto close")
执行结果:
auto connect
sock auto close
============
finally close

 

Python 上下文关系

标签:

原文地址:http://www.cnblogs.com/python-study/p/5876024.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!