【发布时间】:2013-12-27 00:57:46
【问题描述】:
from contextlib import closing
def init_db():
with closing(connect_db()) as db:
with app.open_resource('schema.sql') as f:
db.cursor().executescript(f.read())
db.commit()
这是来自烧瓶教程第 3 步(http://flask.pocoo.org/docs/tutorial/dbinit/#tutorial-dbinit)。我对第 4 行有点好奇。
我必须导入并使用那个 'contextlib.closing()' 方法吗?
当我了解 with 语句时,很多文章都说它在处理后自动关闭文件,如下所示。(与 Final:thing.close() 相同)
with open('filename','w') as f:
f.write(someString);
即使我没有像下面那样使用 contextlib.closing(),有什么区别? 是2.7.6版的,谢谢。
def init_db():
with connect_db() as db:
with app.open_resource('schema.sql') as f:
db.cursor().executescript(f.read())
db.commit()
【问题讨论】:
标签: python with-statement contextmanager