通過配置文件將變量暴露給用戶修改
標准庫模塊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