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语句。
直接来代码,以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语句。
相关文章推荐
- Python的with...as...语句
- python的上下文管理和with语句详解
- Python 的 with 语句
- Python之with语句原理
- 转: 理解Python的With语句
- 浅谈 Python 的 with 语句
- 理解Python的With语句
- 理解Python的With语句
- python :__future__模块简介、命名空间简介、with语句
- python学习笔记:利用contextlib和@contextmanager实现with语句上下文实例
- python文件基础(4)--使用with语句
- 浅谈 Python 的 with 语句(转)
- Python:with语句和上下文管理器对象
- Python with语句上下文管理器两种实现方法分析
- python with魔法语句
- 理解Python的With语句
- python __enter__ 与 __exit__的作用,以及与 with 语句的关系
- python with语句
- 浅谈 Python 的 with 语句
- python 中 with 语句