下面的代码可以在rtfd中找到源码,不过下方代码稍有更改。
1. 封装configparser模块
说明:解析ini格式的配置文件,对configparser模块简单封装,以方便查询配置。参考下方代码,CfgHandler是主要类,它接收一个ini文件,对于section和item可以直接采用属性的方式调用。
示例:
ini文件内容:
[test]
a = 1
在python中调用:
cfg = CfgHandler("ini")
cfg.test.a == cfg.test["a"] == cfg["test"].a == cfg["test"]["a"]
- 代码:
from os import isfile
from configparser import ConfigParser, ExtendedInterpolation
class SectionHandler(object):
def __init__(self, cfg, section):
self._cfg_file = cfg._cfg_file
self._cfg_obj = cfg._cfg_obj
self._section = section
def __str__(self):
return "<%s object at %s, the section is %s(in %s)>" % (
self.__class__.__name__, hex(id(self)),
self._section, self._cfg_file
)
__repr__ = __str__
def __getattr__(self, option):
option = option.lower()
if self._cfg_obj.has_option(self._section, option):
value = self._cfg_obj.get(self._section, option)
if value in ("true", "True"):
value = True
elif value in ("false", "False"):
value = False
return value
raise AttributeError(
"No option %s in section: %s" % (option, self._section)
)
__getitem__ = __getattr__
def get(self, option, converter=None, default=None, err_ignore=True):
try:
value = getattr(self, option)
except AttributeError:
if err_ignore is True:
return default
else:
raise
else:
if callable(converter):
value = converter(value)
return value
def __len__(self):
return len(self._cfg_obj.options(self._section))
class CfgHandler(object):
def __init__(self, cfg=None):
self._cfg_file = cfg
self._cfg_obj = ConfigParser(interpolation=ExtendedInterpolation())
if isfile(self._cfg_file):
self._cfg_obj.read(self._cfg_file)
def __str__(self):
return "<%s object at %s, the config file is %s>" % (
self.__class__.__name__, hex(id(self)), self._cfg_file
)
__repr__ = __str__
def __getattr__(self, section):
section = section.lower()
if self._cfg_obj.has_section(section):
return SectionHandler(self, section)
raise AttributeError("No section: %s" % section)
__getitem__ = __getattr__
@property
def sections(self):
return self._cfg_obj.sections()
def options(self, section):
return self._cfg_obj.options(section)
def items(self, section):
return self._cfg_obj.items(section)
2. click的帮助选项、版本选项
2.1 使用-h显示帮助
默认情况下,click需要使用—help才会显示帮助,不过可以设置这个,示例:
@click.group(context_settings={'help_option_names': ['-h', '--help']})
def cli():
pass
2.2 打印版本
有时候我们想执行 命令 \-v
打印版本,对于click,示例:
def print_version(ctx, param, value):
if not value or ctx.resilient_parsing:
return
click.echo('版本')
ctx.exit()
@click.group()
@click.option('--version', '-v', is_flag=True, callback=print_version,
expose_value=False, is_eager=True)
def cli():
pass