Python 神奇的 main() 签名,如 Perl 6
python 是否有任何方法可以轻松快速地创建 CLI 实用程序,而无需大量参数解析样板?
在 Perl 6 中,MAIN
子 自动解析命令行参数。
有没有办法在 Python 中做类似的事情而无需大量样板?如果没有,最好的方法是什么?我正在考虑一个函数装饰器,它将执行一些内省并做正确的事情。如果还没有类似的东西,我正在思考类似于下面的内容。这是个好主意吗?
@MagicMain
def main(one, two=None, *args, **kwargs):
print one # Either --one or first non-dash argument
print two # Optional --arg with default value (None)
print args # Any other non-dash arguments
print kwargs # Any other --arguments
if __name__ == '__main__':
main(sys.argv)
Does python have any way to easily and quickly make CLI utilities without lots of argument parsing boilerplate?
In Perl 6, the signature for the MAIN
sub automagically parses command line arguments.
Is there any way to do something similar in Python without lots of boilerplate? If there is not, what would be the best way to do it? I'm thinking a function decorator that will perform some introspection and do the right thing. If there's nothing already like it, I'm thinking something like what I have below. Is this a good idea?
@MagicMain
def main(one, two=None, *args, **kwargs):
print one # Either --one or first non-dash argument
print two # Optional --arg with default value (None)
print args # Any other non-dash arguments
print kwargs # Any other --arguments
if __name__ == '__main__':
main(sys.argv)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
Baker 库包含一些方便的装饰器,可以“自动”从方法签名创建 arg 解析器。
例如:
The Baker library contains some convenient decorators to "automagically" create arg parsers from method signatures.
For example:
我不太确定您认为解析样板的内容是什么。 “当前”方法是使用 python 的 argparse 系统。旧系统是 getopt。
I'm not really sure what you consider to be parsing boilerplate. The 'current' approach is to use the argparse system for python. The older system is getopt.
Simon Willison 的
optfunc
模块尝试提供您正在寻找的功能。Simon Willison's
optfunc
module tries to provide the functionality you're looking for.opterator
模块处理这个问题。https://github.com/buchuki/opterator
The
opterator
module handles this.https://github.com/buchuki/opterator
Python 有 getopts 模块来执行此操作。
Python has the getopts module for doing this.
最近,我遇到了 begins 项目,用于装饰和简化命令行处理。
它似乎提供了许多您正在寻找的相同功能。
Recently I came across the begins project for decorating and simplifying command line handling.
It seems to offer a lot of the same functions you are looking for.