python使用配置文件

通过配置文件将变量暴露给用户修改

标准库模块configparser,从而可在配置文件中使用标准格式。

必须使用[files]、[colors]等标题将配置文件分成几部分(section)。标题的名称可随便指定,但必须将它们用方括号括起。

$ cat  area.ini

[numbers]
pi: 3.1415926535893971

[messages]
greeting: Welcome to the area calutation program!
question:  plse enter the radius
result_message: The area is

使用python 读取他

from configparser import  ConfigParser
CONFIGFILE = "area.ini"

config = ConfigParser()
#读取配置文件
config.read(CONFIGFILE)

print(config['messages'].get('greeting'))

radius = float(input(config['messages'].get('question') + ' '))

# 以空格结束以便接着在当前行打印:
print(config['messages'].get('result_message'),end=' ')
print(config['numbers'].getfloat('pi') * radius**2)

配置或控制信息的如下三个来源,你应按这里的排列顺序查询这些来源,让后面的来源覆盖前面的来源:
1,配置文件
2,环境变量
3,在命令行中向程序传递的开关和参数:要处理命令行参数,可直接使用sys.argv;要处理开关(选项),应使用模块argparse

猜你喜欢

转载自www.cnblogs.com/g2thend/p/11813549.html