Python with 用法

  • 打开文件

    with open('em.txt', 'wb') as f:
        f.write('ememem')
  • 线程lock

    lock = threading.Lock()
    # with里面获取lock, 退出with后释放lock
    with lock:
        # Critical section of code
        ...
  • 数据库游标

    db_connection = DatabaseConnection()
    with db_connection as cursor:
        # with里面获取cursor, 退出with后释放cursor
        cursor.execute('insert into ...')
        cursor.execute('delete from ...')
        # ... more operations ...
  • 同时获取lock和数据库游标

    lock = threading.Lock()
    cur = db.cursor()
    with cur as cu, lock as locked:
        ...
  • 请求后关闭

    import urllib, sys
    from contextlib import closing
    
    with closing(urllib.urlopen('http://www.yahoo.com')) as f:
        for line in f:
            sys.stdout.write(line)
全部评论

相关推荐

奔跑的suechil...:怎么评论区这么多打广告的 1.项目考虑是两个,可以加个项目 2.bg一般的话,不建议外卖加点评,99%都过不了简历 3.找项目要么是自己找github好点的开源,要么是评论区找广告去跟着,要么就是星球找项目了 加油友友
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务