配置文件db.json
# This is a json document.
title = "JSON Example"
[database]
server = "192.10.92.10"
ports = [ 5000, 5001, 5002 ]
connection_max = 5000
enabled = true //bool类型
[redis]
ip = "192.10.92.20"
ports = [5000, 5001, 5002]
connection_max = 5000
import urllib.request
import getopt
import sys
import ConfigParser
import commands
cf = ConfigParser.ConfigParser()
# 读取db.json内容
cf.read("db.json")
# 获取所有标题[database,redis]
sections = config.sections()
# 获取database的key,[server,ports,connection_max,enabled]
vals = cf.options("database")
# 获取database的key和value[('server', '"192.10.92.10'), ('ports', [ 5000, 5001, 5002 ]), ('connection_max', '100')]
items = cf.items("database")
#获取database的server元素
server = cf.get("database","server")
# getopt.getopt(args,short,long)
#第一个参数是运行二进制文件接收的参数,它是一个列表,可以通过sys.argv获得
#第二个参数短参数,类似于:python test.py -h,
#第三个参数是长参数类似于:python test.py -help
# sys.argv[1:]是除了指定python文件的其他参数
# 短参数":"代表了当前参数是有值的
#长参数如果要接收值,那必须得在后面加上一个"="
opts,args = getopt.getopt(sys.argv[1:],'-h-f:-v',['help','filename=','version'])
for opt_name,opt_value in opts:
if opt_name in ('-h','--help'):
print(opt_value)
exit()
if opt_name in ('-v','--version'):
version = opt_value
print("version is", version)
exit()
if opt_name in ('-f','--filename'):
fileName = opt_value
print("Filename is ",fileName)
exit()
# 得到linux执行后list列表
dfList=commands.getoutput("df -h").split('\n')
# abc是否匹配正则\W
zz= re.compile(r'\W+')
result = zz.match("abc")
# 等价于compile + match
result = re.match(r'\W+', "abc")