运行python生成器清理代码的最佳方法 [英] best way to run python generator cleanup code
问题描述
我正在尝试编写一个生成器函数,该函数将行从数据库中取出并一次返回一行.但是,我不确定下面标记为**的清理代码是否按照我的想法执行.如果没有,将清理代码放入最后一个yield语句之后执行的生成器本身的最佳方法是什么?我看着捕获StopIteration,但这似乎是由调用者完成的,而不是在生成器中完成的.
I'm trying to write a generator function that gets rows out of a database and returns them one at a time. However, I'm not sure if the cleanup code marked ** below executes as I think it does. If it does not, what is the best way to put cleanup code inside a generator itself that executes after the last yield statement? I looked at catching StopIteration but that seems to be done from the caller, not within the generator.
def MYSQLSelectGenerator(stmt):
...
try:
myDB = MySQLdb.connect(host=..., port=..., user=..., passwd=..., db=...)
dbc=myDB.cursor()
dbc.execute(stmt)
d = "asdf"
while d is not None:
d = dbc.fetchone() #can also use fetchmany() to be more efficient
yield d
dbc.close() #** DOES THIS WORK AS I INTEND, MEANING AS SOON AS d = "None"
except MySQLdb.Error, msg:
print("MYSQL ERROR!")
print msg
推荐答案
您可以使用上下文管理器和with
语句. contextlib
提供
You can use a context manager and the with
statement. contextlib
provides closing
:
from contextlib import closing
myDB = MySQLdb.connect(host=..., port=..., user=..., passwd=..., db=...)
with closing(myDB.cursor()) as dbc:
dbc.execute(stmt)
d = "asdf"
while d is not None:
d = dbc.fetchone() #can also use fetchmany() to be more efficient
yield d
这将在with
块的结尾处自动调用dbc
上的close()
,即使已引发异常.
This will automatically call close()
on dbc
at the end of the with
block, even if an exception has been raised.
这篇关于运行python生成器清理代码的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!