python

profig模块

2020-06-12  本文已影响0人  wit92

profig是一个简单的Python配置库。

1.profig模块特点
2.安装
 pip install profig
3.应用举例

配置文件server.cfg内容如下

[server]
host = 192.168.1.1
port = 9090

首先,我们指定要预期的默认值和类型:

>>> cfg = profig.Config('server.cfg')
>>> cfg.init('server.host', 'localhost')
>>> cfg.init('server.port', 8080)

然后,我们将当前状态与配置文件的状态同步:

>>> cfg.sync()

正如所料,我们可以直接访问更新的值而无需过度努力:

本地主机有,就用本地主机文件的内容;本地主机没有, 就用程序现写进去的

>>> cfg['server.host']
'192.168.1.1'

或者按部分。请注意,端口选项的类型保留:

>>> server_cfg = cfg.section('server')
>>> server_cfg['port']
9090
4.常用API接口

(1).init(key, default, type=None, comment=None)

将键初始化为给定的默认值。
如果类型未提供,则默认值的类型将被使用。
如果已经为key部分设置了一个值,则会强制它键入。
如果提供了注释,则可以以与活动一致的方式将其写入配置文件Format。

Initializes key to the given default value.
If type is not provided, the type of the default value will be used.
If a value is already set for the section at key, it will be coerced to type.
If a comment is provided, it may be written out to the config file in a manner consistent with the active Format.

(2).read(*sources, **kwargs)

读取配置值。
如果提供了来源,请从这些来源中读取。否则,写入源中sources。一种用于格式 源可以使用设置格式。

Reads config values.
If sources are provided, read only from those sources. Otherwise, write to the sources in sources. A format for sources can be set using format.

(3)sync(*sources, **kwargs)

从源读取并将任何更改写回第一个源。
如果提供了源,则仅同步这些源。否则,同步源sources。
format可用于覆盖用于从源读取/写入的格式。

Reads from sources and writes any changes back to the first source.
If sources are provided, syncs only those sources. Otherwise, syncs the sources in sources.
format can be used to override the format used to read/write from the sources.

(4)get(key, default=None)

如果key存在,则返回该值。 否则,返回默认值。
如果未给出default,则默认为None,因此此方法永远不会引发异常。

If key exists, returns the value. Otherwise, returns default.
If default is not given, it defaults to None, so that this method never raises an exception.

上一篇 下一篇

猜你喜欢

热点阅读