with open('/path/to/file', 'r') as f:
f.read()
#管理锁 import threading lock = threading.lock() with lock: #执行一些操作 pass #数据库连接管理 def test_write(): sql = """ #具体的sql语句 """ con = DBConnection() with con as cursor: cursor.execute(sql) cursor.execute(sql) cursor.execute(sql)
class test_query:
def __init__(self):
pass
def query(self):
print('query')
def __enter__(self):
# 如果是数据库连接就可以返回cursor对象
# cursor = self.cursor
# return cursor
print('begin query,')
return self #由于这里没有资源对象就返回对象
def __exit__(self,exc_type,exc_value,traceback):
if traceback is None:
print('End')
else:
print('Error')
# 如果是数据库连接提交操作
# if traceback is None:
# self.commit()
# else:
# self.rollback()
if __name__ == '__main__':
with test_query() as q:
q.query()
@contextmanager
def some_generator(<arguments>):
<setup>
try:
yield <value>
finally:
<cleanup>
import contextlib
@contextlib.contextmanager
def tag(name):
print('<{}>'.format(name))
yield
print('</{}>'.format(name))
if __name__ == '__main__':
with tag('h1') as t:
print('hello')
print('context')
@contextmanager
def locked(lock):
lock.acquire()
try:
yield
finally:
lock.release()
with locked(myLock):
#代码执行到这里时,myLock已经自动上锁
pass
#执行完后会,会自动释放锁
@contextmanager
def myopen(filename, mode="r"):
f = open(filename,mode)
try:
yield f
finally:
f.close()
with myopen("test.txt") as f:
for line in f:
print(line)
@contextmanager
def transaction(db):
db.begin()
try:
yield
except:
db.rollback()
raise
else:
db.commit()
with transaction(mydb):
mydb.cursor.execute(sql)
mydb.cursor.execute(sql)
mydb.cursor.execute(sql)
mydb.cursor.execute(sql)
import contextlib
from urllib.request import urlopen
if __name__ == '__main__':
with contextlib.closing(urlopen('https://www.python.org')) as page:
for line in page:
print(line)
closing也是一个经过@contextmanager装饰的generator,这个generator编写起来其实非常简单:
@contextmanager
def closing(thing):
try:
yield thing
finally:
thing.close()
import contextlib
from urllib.request import urlopen
if __name__ == '__main__':
with contextlib.closing(urlopen('https://www.python.org')) as page,
contextlib.closing(urlopen('https://www.python.org')) as p:
for line in page:
print(line)
print(p)
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有