方式1:argparse
argparse,是Python标准库中推荐使用的编写命令行程序的工具。也可以用于读取配置文件。
字典样式的配置文件*.conf
配置文件test1.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 }}
config.py
# -*- coding: utf-8 -*-"""------------------------------------------------- File Name: mytest.py Description : Author : andy9468 date: 2018/02/27 Copyright: (c) andy9468 2018------------------------------------------------- Change Activity: 2018/02/27: -------------------------------------------------"""import jsonimport sysimport argparsedef 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 jsonconfigdef 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
详见:
方式2:ConfigParser
ConfigParser是Python读取conf配置文件标准的库。
中括号下设置子项的配置文件*.conf、或者*.ini
test2.conf
[game0]ip = 127.0.0.1port = 27182type = 1[game1]ip = 127.0.0.1port = 27183type = 0[game2]ip = 127.0.0.1port = 27184type = 0
test2.py
# -*- coding: utf-8 -*-"""------------------------------------------------- File Name: test2.py Description : Author : andy9468 date: 2018/02/27 Copyright: (c) andy9468 2018------------------------------------------------- Change Activity: 2018/02/27: -------------------------------------------------"""# -*- coding:utf-8 -*-import configparserimport sysdef 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) print(sys.argv)
动态添加配置:
# add cf.add_section('test3') cf.set('test3','id','123') cf.write(open(filename,'w'))
详见:
方式3:用变量(常量)作为配置文件格式。*.py
配置文件:config.py
LISTEN_PORT = 4444USE_EPOLL = True
导入配置:myread.py
import configport_num = config.LISTEN_PORTif config.USE_EPOLL: print(config.USE_EPOLL)
详见: