• 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()
    
  • 相关阅读:
    关于postman返回参数
    字典(dict)
    序列(tuple)
    列表(List)
    字符串截取
    条件及循环语句
    函数
    变量和类型
    post请求
    django学习-5.获取url参数和name的作用
  • 原文地址:https://www.cnblogs.com/shantu/p/4598880.html
Copyright © 2020-2023  润新知