zoukankan      html  css  js  c++  java
  • Python 上下文关系

    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

     另一个示例:

    __author__ = 'alex'
    #coding:utf-8
    import contextlib
    
    @contextlib.contextmanager
    def worker_state(state_list, worker_thread):
        """
        用于记录线程中正在等待的线程数
        """
        state_list.append(worker_thread)
        try:
            print ("begin yield")
            yield
            print ("stop yield")
        finally:
            print ("begin finally")
            state_list.remove(worker_thread)
            print ("stop finally")
    
    
    free_list = []
    current_list = "alex"
    
    with worker_state(free_list,current_list):
        print (123)
        print (456)

    执行结果:
    begin yield
    123
    456
    stop yield
    begin finally
    stop finally
  • 相关阅读:
    最小生成树+BFS J
    Noip 2016
    舒适的路线 (code[vs] 1001)
    拦截导弹 (加了神奇的位运算)
    逃出克隆岛 (codevs 2059)
    回家(洛谷 P1592)
    热浪
    城堡
    笔记 (一道正解思路巧妙的题)
    脱水缩合
  • 原文地址:https://www.cnblogs.com/python-study/p/5876024.html
Copyright © 2011-2022 走看看