• 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
  • 相关阅读:
    从txt读取数据到Cvmat
    PCA之后进行归一化
    vc中调用exe文件并传递参数
    C#安装包过程
    电脑技巧
    DLL文件的创建与调用
    SVM调用方法
    舌顶上腭位置与作用
    KNN算法的實現
    How to Read a Paper
  • 原文地址:https://www.cnblogs.com/python-study/p/5876024.html
Copyright © 2020-2023  润新知