Python读取配置文件和外部参数

配置文件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")
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值