python命令行传参解析(二)------ConfigParser

ConfigParser不仅可以读取配置文件,还可以写入配置文件

首先,命名基本的配置文件: config.ini

本质上:

  • 配置文件包含多个section:[DEFAULT],[bitbucket.org],[topsecret.server.com]
  • 每个section包含若干个键值对,这里的键值是不区分大小写的,写入时会把键值存为小写。
  • 其中,DEFAULT比较特殊,它为其他section中键值提供默认值。
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no

写入

import configparser
config = configparser.ConfigParser()

# 用法1
config["DEFAULT"] = {
    "Country": "China",
    "Max_Iter": "2",
}

# 用法2
config["section_1"] = {}
config["section_1"]["a"] = "2"

# 用法3
config["section_2"] = {}
section2 = config["section_2"]
section2["b"] = "2"

config['DEFAULT']['ForwardX11'] = 'yes'

with open("example.ini", "w") as fp:
    config.write(fp)

执行程序,就可以把配置信息写入到example.ini文件

读取

  • 查看有哪些section
import configparser

config = configparser.ConfigParser()

sections = config.sections()

print(sections)

# 输出为空,因为没有读取配置文件
[]
import configparser

config = configparser.ConfigParser()

config.read("example.ini")
sections = config.sections()

print(sections)

# 输出
['section_1', 'section_2']
#像字典一样,正常读取参数
print(config["DEFAULT"]["country"])
print(config["section_1"]["a"])

# 输出
China
2

ConfigParser解析配置文件时,不区分配置参数类型,统一将其视为字符串读取到内存,然后会根据读取时的数据类型,自行转化成对应的数据类型。

  • ConfigParser支持读取整型、浮点型、布尔型的值
    ** 布尔型:可以通过'yes'/'no','on'/'off','true'/'false'和'1'/'0'等来设定布尔型的参数,然后通过getboolean函数读取对应的参数
[DEFAULT]
country = China
max_iter = 2
a = true
b = off
c = 1

print(config["DEFAULT"].getboolean("a"))
print(config["DEFAULT"].getboolean("b"))
print(config["DEFAULT"].getboolean("c"))

# 输出
True
False
True

** 整型和浮点型


# 通过 getint 和 getfloat 来读取,

[section_1]
a = 2
b = 1.2

print(config["section_1"].getint("a"))
print(config["section_1"].getfloat("b"))

# 输出
2
1.2

#注意: 用getfloat去读取整型参数会把它转化为浮点型,但是不能用getint去读取浮点型数据,会报错。
原文地址:https://www.cnblogs.com/Henry-ZHAO/p/13343745.html