Python读取配置文件
2015-11-20 23:58
519 查看
欢迎转载,转载请注明原文地址:/article/8326782.html
一、argparse
argparse,是Python标准库中推荐使用的编写命令行程序的工具。也可以用于读取配置文件。
1.conf配置文件(test.conf):
2.python代码(test.py):
启动脚本:python test.py test.conf --game=game0
二、ConfigParser
ConfigParser是Python读取conf配置文件标准的库。
1.conf配置文件(test2.conf):
2.Python代码(test2.py):
启动脚本:python test2.py test2.conf
我个人更喜欢第一种方式,因为觉得第一种方式可以很方便操作一个标准json格式的多层的配置,而且更方便命令行过滤,第二种方式不方便操作多层数据且取数据的时候比第一种略微麻烦。
一、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格式的多层的配置,而且更方便命令行过滤,第二种方式不方便操作多层数据且取数据的时候比第一种略微麻烦。
相关文章推荐
- python进阶 内置函数
- 根据输入显示一个人的出生日期(我的第二个python程序)
- python学习笔记-Day04-第三部分(内置函数,map,filter,reduce,yield)
- python学习笔记-Day04-第二部分(lambda表达式)
- python学习笔记(5)
- python学习笔记-Day04-第一部分(冒泡算法的实现)
- python学习笔记(4)
- Python 的判断语句以及输入语句的使用
- pyspark 使用 Ipython
- <LeetCode><Medium>2 Add Two Numbers
- python 写HTML,pyh模块介绍
- Python 入门知识捡漏
- python学习笔记(3)
- Python 内置模块turtle模块的使用
- 5.1.3 date对象
- python实现爬虫统计学校BBS男女比例(二)多线程爬虫
- python学习笔记(2)
- python中input和raw_input有什么区别
- 冰与火之歌:Python的三元表达式
- python学习笔记(1)