Python With语句

从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语句。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值