作为命令行参数的函数的关键字参数

keyword2cmdline的Python项目详细描述


Build Status

命令行参数的关键字

将具有关键字参数的函数转换为具有一行代码的命令行参数。

安装

pipinstallkeyword2cmdline

用法

使用keyword2cmdline模块中的decoratorcommand将函数转换为命令行参数

fromkeyword2cmdlineimportcommand@commanddefmain(text="Hello world",language='en.US',exclamation_number=2,exclamation_sign="!",exclamation=True):...if__name__=='__main__':main()

检查示例examples/hello_world.py

$ python examples/hello_world.py -h
usage: hello_world.py [-h][--exclamation_number EXCLAMATION_NUMBER][--exclamation_sign EXCLAMATION_SIGN][--exclamation EXCLAMATION][--text TEXT][--language LANGUAGE]

optional arguments:
  -h, --help            show this help message and exit
  --exclamation_number EXCLAMATION_NUMBER
  --exclamation_sign EXCLAMATION_SIGN
  --exclamation EXCLAMATION
  --text TEXT
  --language LANGUAGE
$ python examples/hello_world.py
Hello world!!
>>> from examples.hello_world import main
>>> main.set_sys_args([])()
Hello world!!
$ python examples/hello_world.py --exclamation_number 10
Hello world!!!!!!!!!!
>>> from examples.hello_world import main
>>> main.set_sys_args("--exclamation_number 10".split())()
Hello world!!!!!!!!!!
$ python examples/hello_world.py --language hi.IN
नमस्ते दुनिया!!
>>> from examples.hello_world import main
>>> main.set_sys_args("--language hi.IN".split())()
नमस्ते दुनिया!!

对于布尔变量,任何字符串都是True,但空字符串“”是False(可以自定义)

$ python examples/hello_world.py --exclamation ''
Hello world
>>> from examples.hello_world import main
>>> main.set_sys_args( ["--exclamation", ""])()
Hello world

若要向ArgumentParser.add_argument()添加帮助和更多自定义项,请参见中的示例 examples/hello_world_customizations.py。基本上是导入一个伪类opts 从关键字2cmdline,然后像optsdict一样传递所有参数

fromkeyword2cmdlineimportcommand,opts@commanddefmain(text="Hello world",language='en.US',exclamation_number=2,exclamation_sign="!",exclamation=opts(default=True,type=bool,help="""Whether to use exclamation sign or not. Use empty string '' for False""")):...if__name__=='__main__':main()

请求帮助将打印关键字帮助。

$ python examples/hello_world_customizations.py -h
usage: hello_world_customizations.py [-h][--exclamation_sign EXCLAMATION_SIGN][--exclamation EXCLAMATION][--text TEXT][--language LANGUAGE][--exclamation_number EXCLAMATION_NUMBER]

Prints hello world with desired number of exclamation signs

optional arguments:
  -h, --help            show this help message and exit
  --exclamation_sign EXCLAMATION_SIGN
  --exclamation EXCLAMATION
                        Whether to use exclamation sign or not. Use empty
                        string ''for False.
  --text TEXT
  --language LANGUAGE
  --exclamation_number EXCLAMATION_NUMBER

支持变量**kwargs

(v1.0中的新功能)

>>> from keyword2cmdline import command
>>> first = lambda xs: xs[0]
>>> @command
... def main(text="sum", **kw):
...     return dict(kw, text=text)
>>> _ = main.set_sys_args(sys_args = "--text sum --a 1 --b 2 --c 3".split())
>>> list(sorted(main().items(), key=first))
[('a', '1'), ('b', '2'), ('c', '3'), ('text', 'sum')]

支持点击式布尔分析器

(v1.0中的新功能)

fromkeyword2cmdlineimportclick_like_command@click_like_commanddefmain(text="Hello world",language='en.US',exclamation_number=2,exclamation_sign="!",exclamation=True):...
$ python examples/hello_world.py --exclamation False
Hello world
>>> from examples.hello_world_click import main
>>> main.set_sys_args( ["--exclamation", "False"])()
Hello world

支持argcomplete、list、dict和enum

(v1.3.0中的新功能)

listdict使用json.loads解析。dict与 默认的dict参数。enum.Enum转换为字符串,并且 相应的字符串可以转换回枚举对象。方便 类keyword2cmdline.EnumChoice用于使用enum的缩写 对象,该对象可能使用长名称一致地支持argcomplete功能。

>>> from keyword2cmdline import command, EnumChoice
>>> @command
... def main(text="Hello world",
...          language=EnumChoice('Lang', 'en_US hi_IN').en_US,
...          exclamation_props=dict(number=2),
...          exclamation=True):
...     return sorted(locals().items())
...
>>> main.set_sys_args([])()
[('exclamation', True), ('exclamation_props', {'number': 2}), ('language', <Lang.en_US: 1>), ('text', 'Hello world')]
>>> main.set_sys_args(["--exclamation", ""])()
[('exclamation', False), ('exclamation_props', {'number': 2}), ('language', <Lang.en_US: 1>), ('text', 'Hello world')]
>>> main.set_sys_args(["--language", "hi_IN"])()
[('exclamation', True), ('exclamation_props', {'number': 2}), ('language', <Lang.hi_IN: 2>), ('text', 'Hello world')]
>>> main.set_sys_args(["--exclamation_props", '{"number": 3}'])()
[('exclamation', True), ('exclamation_props', {'number': 3}), ('language', <Lang.en_US: 1>), ('text', 'Hello world')]

>>> from keyword2cmdline import click_like_command
>>> @click_like_command
... def main(text="Hello world",
...          language=EnumChoice('Lang', 'en_US hi_IN').en_US,
...          exclamation_props=dict(number=2),
...          exclamation=True):
...     return sorted(locals().items())
...
>>> main.set_sys_args(["--exclamation", "False"])()
[('exclamation', False), ('exclamation_props', {'number': 2}), ('language', <Lang.en_US: 1>), ('text', 'Hello world')]

使用命令配置支持递归配置

(v2.0.0中的新功能)

递归函数通过构造函数的部分来处理 用@command_config标记的。

>>> from keyword2cmdline import command, EnumChoice, command_config
>>> @command_config
... def exclamation(number=2,
...                 sign="!",
...                 use=True):
...     return sorted(locals().items())
>>> @command
... def main(text="Hello world",
...          language=EnumChoice('Lang', 'en_US hi_IN').en_US,
...          exclamation=exclamation):
...     return [("text", text), ("language", language)] + [
...            ("exclamation." + k, v)
...            for k, v in sorted(exclamation.keywords.items()) ]
>>> main.set_sys_args(["--exclamation.use", "True", "--exclamation.sign", "?"])()
[('text', 'Hello world'), ('language', <Lang.en_US: 1>), ('exclamation.number', 2), ('exclamation.sign', '?'), ('exclamation.use', True)]


A click like handling of booleans is available with `click_like_command_config`
and `click_like_command`.

``` python-console
>>> from keyword2cmdline import click_like_command, EnumChoice, click_like_command_config
>>> @click_like_command_config
... def exclamation(number=2,
...                 sign="!",
...                 use=True):
...     return sorted(locals().items())
>>> @click_like_command
... def main(text="Hello world",
...          language=EnumChoice('Lang', 'en_US hi_IN').en_US,
...          exclamation=exclamation):
...     return [("text", text), ("language", language)] + [
...            ("exclamation." + k, v)
...            for k, v in sorted(exclamation.keywords.items()) ]
>>> main.set_sys_args(["--exclamation.use", "False", "--exclamation.sign", "?"])()
[('text', 'Hello world'), ('language', <Lang.en_US: 1>), ('exclamation.number', 2), ('exclamation.sign', '?'), ('exclamation.use', False)]

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
我可以用C++代码使用java代码吗?   java使用JSR303在派生类中提供更具体的约束   java在这个查找唯一路径数算法中我做错了什么?   java如何为2个不同的服务提供商使用2个不同的SSL证书?   java在Gridview上绘制文本   java使用连接for循环构建字符串名   java StringBuilder拆分无法处理某些文件   java事件关注EditText   Java Web Start“找不到URL的缓存资源”   java程序从命令行运行的速度比在Eclipse中慢   java为什么HttpServletRequest会截断#字符上的url输入?   java自定义折叠工具栏平滑标题大小调整   使用Mockito对安卓 java中调用另一个静态函数的函数进行单元测试   http在java客户机中使用cachecontrol头   java如何使用。是否使用Delimiter从输入文件中排除标点符号和数字?   使用上下文作为参数/参数的java   java更有效地从Jar中提取文件   java为多个JButton提供相同的actionListener