python 之 ConfigParser module简用说明

来源:互联网 发布:win7网络图标显示红叉 编辑:程序博客网 时间:2024/05/17 08:37

在使用IMAP4作登陆邮箱时涉及到要不要使用明文密码的问题,其中一种方法是通过读取配置文件来获取用户名和密码。读取配置文件有一块相关的模块是 ConfigParser module,下面简单记录下其调用方法;

#!/usr/bin/env python#-*- coding: utf-8 -*-#filename:config_parser_.pyimport ConfigParsercf = ConfigParser.ConfigParser()#初始化实例content = cf.read('config.txt')#读取配置文件print 'content:\n %s' % contentsections = cf.sections()#读取【】中的section内容print 'sections:\n %s' % sectionsoptions = cf.options('db')#获取对应section下的option 即:dbprint 'options:\n %s' % optionsitems = cf.items('db')#获取指定section的配置信息print 'items:\n %s' % itemsdb_host = cf.get('db', 'db_host')#可以按照指定类型获取option的信息db_port = cf.getint('db', 'db_port')#比如整形db_user = cf.get('db', 'db_user')db_pass = cf.get('db','db_pass')concurrent_test = cf.get('concurrent', 'thread')print 'db_host:%s' % db_hostprint 'db_port:%s' % db_portprint 'db_user:%s' % db_userprint 'db_pass:%s' % db_passprint 'concurrent_test:\n %s' % concurrent_testcf.set('db', 'db_test', 'test2')#设置option的值,可以重写cf.write(open('config.txt', 'w'))#需要写回保存items = cf.items('db')print 'After the set, items changed to :\n %s' % itemscf.add_section('new')#追加新的sectioncf.set('new', 'int', '555')#设置option值cf.set('new', 'str', 'python is python')cf.write(open('config.txt', 'w'))items = cf.items('new')print 'After the add, items changed to :\n %s' % itemscf.remove_option('new', 'int')#移除section为new中的其中option值items = cf.items('new')cf.write(open('config.txt', 'w'))#需要写回保存print 'After the option remove, items changed to :\n %s' % itemscf.remove_section('new')#移除整个sectionitems = cf.items('new')cf.write(open('config.txt', 'w'))print 'After the section remove, items changed to :\n %s' % items

原始config.txt文件:

[db]db_host = 127.0.0.1db_port = 22db_user = rootdb_pass = passwddb_test = 23453456465[concurrent]thread = 10processor = 20

输出:

>>> ================================ RESTART ================================>>> content: ['config.txt']sections: ['db', 'concurrent']options: ['db_host', 'db_port', 'db_user', 'db_pass', 'db_test']items: [('db_host', '127.0.0.1'), ('db_port', '22'), ('db_user', 'root'), ('db_pass', 'passwd'), ('db_test', '23453456465')]#可以按照指定类型获取option的信息,cf.getint()db_host:127.0.0.1db_port:22db_user:rootdb_pass:passwdconcurrent_test: 10After the set, items changed to : [('db_host', '127.0.0.1'), ('db_port', '22'), ('db_user', 'root'), ('db_pass', 'passwd'), ('db_test', 'test2')]After the add, items changed to : [('int', '555'), ('str', 'python is python')]After the option remove, items changed to : [('str', 'python is python')]#int被移除了Traceback (most recent call last):#这里报错很正常,因为理论上new这个section已经remove了,所以找不到  File "D:\Python\tmp\config_parser_.py", line 50, in <module>    items = cf.items('new')  File "C:\Python27\lib\ConfigParser.py", line 634, in items    raise NoSectionError(section)NoSectionError: No section: 'new'>>> 
修改后的config.txt文件内容
[db]db_host = 127.0.0.1db_port = 22db_user = rootdb_pass = passwddb_test = test2[concurrent]thread = 10processor = 20[new]#这个理论上已经移除,但是仍存在,比较奇怪?????why?str = python is python

实例应用:

#!/usr/bin/env python#-*- coding: utf-8 -*-#filename:receive_imap_email.pyimport imaplib, os, ConfigParser def user_login(verbose=False):    #Read the config file    config = ConfigParser.ConfigParser()    config.read(r'D:\Python\tmp\config.txt')#从本配置文件中读取    #Connect to the server    hostname = config.get('server', 'hostname')#获取server下的hostname    if verbose:        print 'Connecting to', hostname        m = imaplib.IMAP4(hostname)    #Login to the account    username = config.get('account', 'username')#获取account下的username和passwd    passwd = config.get('account', 'passwd')    if verbose:        print 'Logging in as ', username        m.login(username,passwd)        print m.select()        print m.check()#检查邮件        m.close()        m.logout()user_login(verbose=True)

config.txt文件内容:

[account]username = dxx_studypasswd = xue*****[server]hostname = imap.163.com

输出:

>>> ================================ RESTART ================================>>> Connecting to imap.163.comLogging in as  dxx_study('OK', ['175'])('OK', ['CHECK completed'])>>> 

这种应该在有大量用户的情况下使用配置文件估计比较好,免得一个个输入或者在程序中占用大量位置,修改也比较方便;






参考文章:http://blog.chinaunix.net/uid-25890465-id-3312861.html



原创粉丝点击