您的位置:首页 > 编程语言 > Python开发

Python With语句

2013-12-14 10:52 711 查看
从Java转过来,习惯性try, catch, finally ,然后在 finally里面 释放各种资源。 Python 中不用自己finally释放资源。使用with上下文管理器。

直接来代码,以Python 操作MySQL为例。

#! -*-coding: utf-8 -*-

import sys

import logging

import MySQLdb

from contextlib import closing #此处是关键,凡是实现此closing的类 都可以用with语句释放资源

#db configs

HOST = '127.0.0.1'

USER = 'user'

PASSWORD = 'user'

DBNAME = "test"

def execute_read_sql(sql_str):

with closing(get_db_conn(HOST, USER, PASSWORD, DBNAME)) as conn:

cursor = conn.cursor()

cursor.execute(sql_str)

result = cursor.fetchall()

conn.commit() #即使是读语句,也 commit(),不commit也能读出数据,仅风格

return result

def execute_write_sql(sql_strs):

with closing(get_db_conn(HOST, USER, PASSWORD, DBNAME)) as conn:

cursor = conn.cursor()

for sql in sql_strs:

cursor.execute(sql)

conn.commit() # lays out of for, commit only once

def get_db_conn(host, username, password, dbname):

try:

conn = MySQLdb.connect(host, username, password, dbname, charset="utf8")

return conn

except Exception:

logging.error("fail to connect %s %s" % (host, dbname))

sys.exit()

其他很多 对象,如 http的 connection, 文件对象 , 管道 , 锁 等等,只要是可以使用 contextlib.closing 释放的都能用 with语句。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: