简单处理用户配置
项目描述
PySCFG - Python简单配置
为您的Python项目存储/加载/修改配置的简单解决方案。
版本:0.2.0
贡献者:suppetia
设置
通过pip安装
pip install pyscfg
从源安装
git clone https://github.com/suppetia/pyscfg.git
cd pyscfg
python setup.py install
入门
此库允许像使用字典一样简单地在程序重启后工作,访问/更新/删除存储在文件中的配置。使用“方括号语法”像使用字典一样访问配置,库将处理所有I/O并保持配置文件最新。
在当前开发阶段,支持YAML和JSON文件来存储配置。
! 所有配置键必须是字符串,如果它们包含点(“.”),则被视为多级键。
要开始,初始化一个SimpleConfigs实例
from pyscfg import SimpleConfigs
# uses file 'configs.yml' (default) to store the configurations
cfg = SimpleConfigs()
# To store the configs in a specific file, pass the path to configuration file.
cfg = SimpleConfigs("data/configs.yml")
如果data/configs.yml
看起来像
a:
b: value
c: value2
d: value3
可以使用以下任何一种方式访问'value':
cfg["a.b"]
cfg["a"]["b"]
cfg.get("a.b")
cfg["a"].get("b")
cfg.get("a").get("b")
cfg.get("a")["b"]
调用
cfg["a.d"]
将引发一个KeyError
,而
cfg["a"].get("d") # returns None
cfg["a"].get("d", default=None) # returns None
cfg["a"].get("d", default="foo") # returns "foo"
如果键未存储在配置中,则返回默认值。
要提取一组配置(配置文件中的一个层)作为字典,请使用
cfg["a"].as_dict() # or
dict(cfg["a"])
同样,更新或添加新的配置键也可以这样工作
cfg["a.b"] = "new_value"
cfg["a"]["b"] = "new_value"
...
cfg["e"] = "another new value"
...
# to add a group of parameters use a dict:
cfg["f"] = {"g": 1, "h": 1e10}
在这些更改之后,data/configs.yml
文件将看起来像这样
a:
b: new value
c: value2
d: value3
e: another new value
要删除一个键,请使用以下任何一种方式
cfg.remove("e")
del cfg["e"]
# to retrieve the item to be removed or to safely remove a key use dict-like pop-method
cfg.pop("e") # returns "another new value"
cfg.pop("non existing key") # returns None
cfg.pop("non existing key", default=42) # returns 42
存储在字典中的默认值可以传递给构造函数。如果键不在配置中,则将这些值分配。配置文件将更新。
这可能对首次为应用程序创建配置文件很有用,并且这些配置可能会由用户稍后更改。
from pyscfg import SimpleConfigs
defaults = {
"foo": "John",
"bar": "Doe",
"num": 0
}
# uses file 'configs.yml' (default) to store the user configurations
cfg = SimpleConfigs(defaults=defaults)
print(cfg["num"]) # prints 0
if user_chooses_this_option:
cfg["num"] = 1
else:
cfg["num"] = -1
print(cfg["num"]) # prints 1 or -1
您还可以将默认设置写入配置文件(支持:YAML,JSON)并将其传递给构造函数。
# uses file 'default_cfg.yml' in subdirectory 'data' to load the default configuration values
cfg = SimpleConfigs(defaults="data/default_cfg.yml")
项目详情
下载文件
下载适用于您平台的文件。如果您不确定选择哪一个,请了解更多关于安装包的信息。
源分发
pyscfg-0.2.1.tar.gz (6.2 kB 查看哈希值)
构建分发
pyscfg-0.2.1-py3-none-any.whl (7.6 kB 查看哈希值)
关闭
pyscfg-0.2.1.tar.gz的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | b6201ff76c46b9492f1f3a2cfd89b0cb474dc506f144da370a565aee2307e072 |
|
MD5 | e12d9859016090f761bc938f8e832c17 |
|
BLAKE2b-256 | 39f9d0213856007dc506f0c7111762f0e1eb51cb12810381d9af2cf2e61a64b0 |
关闭
pyscfg-0.2.1-py3-none-any.whl的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 9e0b8bba31cd2e4606dcbea885f5732c48e4a284151e34f201ceb41ed6b24f6d |
|
MD5 | ab58b86fa25aa24c8b39c14336c04b05 |
|
BLAKE2b-256 | 6724cc400a168e73f0c8455ede955317bd67ed77304782a4025460d11a9b2ead |