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 1028 母函数分析
    尼姆博弈的典型例题
    HDOJ1232 畅通工程 DFS
    第一个八皇后
    HDOJ 1242
    我的“插入算法”实现
    第五讲 this 类变量 类方法
    我的“二分查找算法”实现
    我对锤子ROM 功能的看法——视觉篇
    第六讲 Java 四大特性:抽象 封装 继承 多态
  • 原文地址:https://www.cnblogs.com/shantu/p/4598880.html
Copyright © 2011-2022 走看看