zoukankan      html  css  js  c++  java
  • Python with 用法

    with open('em.txt', 'w') as f:
        f.write('ememem')
    

    等价于

    tmp = open('em.txt', 'w')
    f = tmp.__enter__()
    #tmp == f  True
    f.write('ememem')
    f.__exit__()
    print(f)
    # <_io.TextIOWrapper name='em.txt' mode='w' encoding='cp65001'>
    
    • 打开文件

      with open('em.txt', 'w') 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)
      
  • 相关阅读:
    33. Search in Rotated Sorted Array
    文章
    导航
    页眉和页脚
    渐变
    图像翻转与子画面
    背景图像定位
    背景图像
    使用css将图像居中
    使用CSS将图像对齐
  • 原文地址:https://www.cnblogs.com/twfb/p/11606147.html
Copyright © 2011-2022 走看看