python 常用模組之ConfigParser

來源:互聯網
上載者:User

標籤:

在程式中使用設定檔來靈活的配置一些參數是一件很常見的事情,設定檔的解析並不複雜,在Python裡更是如此,在官方發布的庫中就包含有做這件事情的庫,那就是ConfigParser, Python ConfigParser模組解析的設定檔的格式比較象ini的設定檔格式

下面用執行個體說明如下:

設定檔db.conf 
[db]db_host=10.1.10.15db_port=3306db_user=rootdb_pass=59222999
串連資料程式如下:
#!/usr/bin/env python# coding:utf8#author: [email protected]import ConfigParser,string,os,sysimport MySQLdbdbconf = ConfigParser.ConfigParser()dbconf.read("db.conf")#return sections = dbconf.sections()print s,‘\n‘o = dbconf.options(‘db‘)print ‘option:‘,o,‘\n‘v = dbconf.items("db")print ‘db:‘,v,‘\n‘#可以按照類型讀取出來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,#connectconn = MySQLdb.connect(host = db_host,user = db_user,passwd = db_pass, port = int(db_port),db = ‘myapp‘)cursor = conn.cursor()#select tablest = cursor.execute(‘‘‘show tables‘‘‘)for tr in cursor.fetchall():    print tr,#select tables resultn = cursor.execute(‘select * from auth_user‘)for rr in cursor.fetchall():    print rr,conn.close()

python 常用模組之ConfigParser

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.