1.ConfigParser 解析配置文件
ConfigParser 模块包含了 ConfigParser 类。一个 ConfigParser
对象可以同时解析多个配置文件,一般情况下,我们使用 ConfigParser
解析一个配置文件。
allow_no_value的默认值是False,表示是否允许在配置文件中没有值的
情况。默认每个配置项都有值。特殊情况,没有值,认为是true;
--允许存在空值。
vi my.cnf
[client]
port=3306
user=mysql
password=mysql
host=127.0.0.1
[mysqld]
basedir=/usr
datadir=/var/lib/mysql
tmpdir=/tmp
skip-external-locking
vi configparser.py
import ConfigParser
cf = ConfigParser.ConfigParser(allow_no_value=True)
cf.read('my.cnf')
--ConfigParser 对象的方法读取方法。
sections:返回一个包含所有章节的列表
has_section: 判断章节是否存在。
items:以元组形式返回所有选项。
options:返回一个包含章节下所有选项的列表。
has_option:判断某个选项是否存在。
get,getboolean,getint,getfload: 获取选项的值。
vi configparser.py
import ConfigParser
cf = ConfigParser.ConfigParser(allow_no_value=True)
cf.read('my.cnf')
print(cf.sections())
print(cf.has_section('client'))
print(cf.options('client'))
print(cf.has_option('client','user'))
print(cf.get('client','host'))
print(cf.getint('client','port'))
[root@mysql1 python]# python configparser.py
['client', 'mysqld']
True
['port', 'user', 'password', 'host']
True
127.0.0.1
3306
--ConfigParser 修改配置文件的方法。
remove_section: 删除一个章节
add_section: 添加一个章节。
remove_option: 删除一个选项。
set :添加一个选项。
write:将 ConfigParser 对象中的数据保存到配置文件中。
cf.remove_section('client') #删除client章节。
cf.add_section('mysql') #添加一个mysql章节
cf.set('mysql','host','127.0.0.1') #添加参数。
cf.write(open('my_copy.cnf'),'2') #写入配置文件
-----------------------------
import ConfigParser
cf = ConfigParser.ConfigParser(allow_no_value=True)
cf.read('my_copy.cnf')
print(cf.sections())
print(cf.has_section('mysql'))
print(cf.options('client'))
print(cf.has_option('client','user'))
print(cf.get('client','host'))
print(cf.getint('client','port'))
cf.remove_section('client')
cf.add_section('mysql')
cf.set('mysql','host','127.0.0.1')
cf.set('mysql','port','3306')
cf.write(open('my_copy.cnf','w'))
print(cf.options('mysql'))
--输出。
[root@mysql1 python]# python configparser.py
['client', 'mysqld']
True
['port', 'user', 'password', 'host']
True
127.0.0.1
3306
['host']
--查看修改后的文件。
[root@mysql1 python]# cat my_copy.cnf
[mysqld]
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
skip-external-locking
[mysql]
host = 127.0.0.1
由此可见,删除章节,会把章节名称及章节下的参数全部删除。
2.使用 argparse 解析命令行参数。
ConfigParser 解析参数文件。
argparse 解析命令行参数。
argparse 是标准库中解析命令行参数的模块,用来替代 optparse模块。
argparse 能够根据程序中的定义从 sys.argv 中解析出这些参数。
并自动生成帮助和使用信息。
ArgumentParser :
为应用程序添加参数选项需要用 ArgumentParser 对象的 add_argument方法。
add_argument(name ,atction,nargs,const,default,type,choise,required,help,
metavar,dest)
name/flag:参数的名字。
action:遇到参数时的动作,默认值是store;
nargs:参数个数。"*" 表示0或多个,"+" 号表示1或多个。
const :action 和 nargs 需要的常量值。
default:不指定参数时的默认值。
type:参数的类型
choices:参数允许的值。
required: 可选参数是否可以省略。
help: 参数的帮助信息。
metavar: 在 usage 说明中的参数名称。
dest:解析后的参数名称。
parse_args 方法解析参数。返回一个namespace对象。
--案例
vi argparser.py
import argparse
def _argparse():
parser=argparse.ArgumentParser(description="This is description")
parser.add_argument('--host',action='store',dest='server',
default='localhost',help='connect to host')
parser.add_argument('-t',action='store_true',default=False,
dest='boolean_switch',help='Set a switch to true')
return parser.parse_args()
def main():
parser = _argparse()
print(parser)
print('host =',parser.server)
print('boolean_switch=',parser.boolean_switch)
if __name__=='__main__':
main()
[root@mysql1 python]# python argparser.py
Namespace(boolean_switch=False, server='localhost')
('host =', 'localhost')
('boolean_switch=', False)
[root@mysql1 python]# python argparser.py --host=192.168.1.11 -t
Namespace(boolean_switch=True, server='192.168.1.11')
('host =', '192.168.1.11')
('boolean_switch=', True)
[root@mysql1 python]# python argparser.py --help
usage: argparser.py [-h] [--host SERVER] [-t]
This is description
optional arguments:
-h, --help show this help message and exit
--host SERVER connect to host
-t Set a switch to true
(2)模仿MySQL客户端的命令
vi mysql_client.py
import argparse
def _argparse():
parser=argparse.ArgumentParser(description='A Python-MySQL client')
parser.add_argument('--host',action='store',dest='host',required=True,help='connect to host')
parser.add_argument('-u','--user',action='store',dest='user',required=True,help='user for login')
parser.add_argument('-p','--password',action='store',dest='password',required=True,help='Password to use when coenncting to mysql')
parser.add_argument('-P','--port',action='store',dest='port',default=3306,type=int,help='port number to user for connection or 3306 for default')
parser.add_argument('-v','--version',action='version',version='%(prog)s 0.1')
return parser.parse_args()
def main():
parser=_argparse()
conn_args=dict(host=parser.host,user=parser.user,password=parser.password,port=parser.port)
print(conn_args)
if __name__=='__main__':
main()
[root@mysql1 python]# python mysql_client.py --help
usage: mysql_client.py [-h] --host HOST -u USER -p PASSWORD [-P PORT] [-v]
A Python-MySQL client
optional arguments:
-h, --help show this help message and exit
--host HOST connect to host
-u USER, --user USER user for login
-p PASSWORD, --password PASSWORD
Password to use when coenncting to mysql
-P PORT, --port PORT port number to user for connection or 3306 for default
-v, --version show program's version number and exit