zoukankan      html  css  js  c++  java
  • python 常用模块之ConfigParser

    在程序中使用配置文件来灵活的配置一些参数是一件很常见的事情,配置文件的解析并不复杂,在Python里更是如此,在官方发布的库中就包含有做这件事情的库,那就是ConfigParser, Python ConfigParser模块解析的配置文件的格式比较象ini的配置文件格式

    下面用实例说明如下:

    配置文件db.conf 

    [db]
    db_host=10.1.10.15
    db_port=3306
    db_user=root
    db_pass=59222999
    

    连接数据程序如下:

    #!/usr/bin/env python
    # coding:utf8
    #author: wangqiankun@lashou-inc.com
    
    
    import ConfigParser,string,os,sys
    import MySQLdb
    
    
    dbconf = ConfigParser.ConfigParser()
    dbconf.read("db.conf")
    
    #return section
    
    s = dbconf.sections()
    print s,'
    '
    o = dbconf.options('db')
    print 'option:',o,'
    '
    
    v = dbconf.items("db")
    print 'db:',v,'
    '
    
    #可以按照类型读取出来
    
    db_host = dbconf.get("db","db_host")
    db_port = dbconf.get("db",'db_port')
    db_user = dbconf.get('db','db_user')
    db_pass = dbconf.get('db','db_pass')
    print db_host,db_port,db_user,db_pass,
    
    
    #connect
    conn = MySQLdb.connect(host = db_host,user = db_user,passwd = db_pass, port = int(db_port),db = 'myapp')
    cursor = conn.cursor()
    
    #select tables
    t = cursor.execute('''show tables''')
    for tr in cursor.fetchall():
        print tr,
    #select tables result
    n = cursor.execute('select * from auth_user')
    for rr in cursor.fetchall():
        print rr,
    
    conn.close()
    
  • 相关阅读:
    Hdoj 3697 Selecting courses 【贪心】
    nginx 反向代理
    嵌入式交叉编译环境搭建
    OpenWrt编译
    OpenWrt for vmware 从openwrt.org下载10.03.1 或是自己下载最新的源码进行编译生成x86 vmdk格式
    ubuntu centos debina
    openWRT
    C++ classics
    tomcat配置访问日志,访问首页主目录
    apache http配置https
  • 原文地址:https://www.cnblogs.com/shantu/p/4598880.html
Copyright © 2011-2022 走看看