traitscli - 基于类特征的CLI生成器
项目描述
Traits CLI基于Enthought的Traits库。
一些优点
自动设置命令行参数的类型(int/float/…)。
帮助字符串生成。
“深层值”配置:例如,--dict['a']['b']['c']=1 等同于Python代码中的 obj.dict['a']['b']['c'] = 1。
嵌套类配置:例如,--sub.attr=val 等同于Python代码中的 obj.sub.attr = val。
支持参数文件(ini/conf,json,yaml等)。从文件中加载参数然后设置属性。
链接
安装
pip install traitscli
依赖项
argparse(用于Python < 2.7)
示例
源代码
from traitscli import TraitsCLIBase from traits.api import Bool, Float, Int, Str, Enum class SampleCLI(TraitsCLIBase): ''' Sample CLI using `traitscli`. Example:: %(prog)s --yes # => obj.yes = True %(prog)s --string something # => obj.string = 'string' %(prog)s --choice x # => raise error (x is not in {a, b, c}) ''' # These variables are configurable by command line option yes = Bool(desc='yes flag for sample CLI', config=True) no = Bool(True, config=True) fnum = Float(config=True) inum = Int(config=True) string = Str(config=True) choice = Enum(['a', 'b', 'c'], config=True) # You can have "internal" attributes which cannot be set via CLI. not_configurable_from_cli = Bool() def do_run(self): names = self.class_trait_names(config=True) width = max(map(len, names)) for na in names: print "{0:{1}} : {2!r}".format(na, width, getattr(self, na)) if __name__ == '__main__': # Run command line interface SampleCLI.cli()
示例运行
$ python sample.py --help usage: sample.py [-h] [--choice {a,b,c}] [--fnum FNUM] [--inum INUM] [--no] [--string STRING] [--yes] Sample CLI using `traitscli`. Example:: sample.py --yes # => obj.yes = True sample.py --string something # => obj.string = 'string' sample.py --choice x # => raise error (x is not in {a, b, c}) optional arguments: -h, --help show this help message and exit --choice {a,b,c} (default: a) --fnum FNUM (default: 0.0) --inum INUM (default: 0) --no (default: True) --string STRING (default: ) --yes yes flag for sample CLI (default: False) $ python sample.py --yes --choice a string : '' no : True fnum : 0.0 choice : 'a' inum : 0 yes : True $ python sample.py --inum invalid_argument usage: sample.py [-h] [--choice {a,b,c}] [--fnum FNUM] [--inum INUM] [--no] [--string STRING] [--yes] sample.py: error: argument --inum: invalid int value: 'invalid_argument'