您的位置:首页 > 编程语言 > Python开发

Python读取配置文件

2015-11-20 23:58 519 查看
欢迎转载,转载请注明原文地址:/article/8326782.html

一、argparse

argparse,是Python标准库中推荐使用的编写命令行程序的工具。也可以用于读取配置文件。

1.conf配置文件(test.conf):

{
"game0":
{
"ip":"127.0.0.1",
"port":27182,
"type":1
},
"game1":
{
"ip":"127.0.0.1",
"port":27183,
"type":0
},
"game2":
{
"ip":"127.0.0.1",
"port":27184,
"type":0
}
}


2.python代码(test.py):

# -*- coding:utf-8 -*-

import json
import sys
import argparse

def parse_args(args):
parser = argparse.ArgumentParser(prog="GameServer")
parser.add_argument('configfile', nargs=1, type=str, help='')
parser.add_argument('--game', default="game", type=str, help='')
return parser.parse_args(args)

def parse(filename):
configfile = open(filename)
jsonconfig = json.load(configfile)
configfile.close()
return jsonconfig

def main(argv):
args = parse_args(argv[1:])
print "args:",args
config = parse(args.configfile[0])
info = config[args.game]
_ip = info['ip']
_port = info['port']
print "type:",type(_port)
_type = info['type']
print "print:%s,%d,%d"%(_ip,_port,_type)

if __name__ == '__main__':
main(sys.argv)


启动脚本:python test.py test.conf --game=game0

二、ConfigParser
ConfigParser是Python读取conf配置文件标准的库。

1.conf配置文件(test2.conf):

[game0]
ip = 127.0.0.1
port = 27182
type = 1

[game1]
ip = 127.0.0.1
port = 27183
type = 0

[game2]
ip = 127.0.0.1
port = 27184
type = 0


2.Python代码(test2.py):

# -*- coding:utf-8 -*-

import ConfigParser
import sys

def parse_args(filename):
cf = ConfigParser.ConfigParser()
cf.read(filename)

#return all sections
secs = cf.sections()
print "sections:",secs

#game0 section
game0 = cf.options("game0")
print "game0:",game0

items = cf.items("game0")
print "game0 items:",items

#read
_ip = cf.get("game0","ip")
_port = cf.getint("game0", "port")
_type = cf.getint("game0", "type")
print "print:%s,%d,%d"%(_ip,_port,_type)

def main(argv):
parse_args(argv[1])

if __name__ == '__main__':
main(sys.argv)

启动脚本:python test2.py test2.conf

我个人更喜欢第一种方式,因为觉得第一种方式可以很方便操作一个标准json格式的多层的配置,而且更方便命令行过滤,第二种方式不方便操作多层数据且取数据的时候比第一种略微麻烦。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: