添加既改变行为又存储参数的选项

发布于 2024-09-10 05:48:37 字数 253 浏览 0 评论 0原文

使用 argparse 模块,是否可以对给定参数执行多个操作?

具体来说,我想提供一个带有 nargs='?'-l/--list 选项,这将改变程序从其主要功能转变为提供有关一组中所有可能性或有关一种特定可能性的信息。

通常会有一个命名空间属性,其中包含解析后要调用的函数;我希望 -l 选项既可以更改此属性,也可以选择将其参数存储在不同的属性中。

这可能吗?

Using the argparse module, is it possible to perform multiple actions for a given argument?

Specifically, I'd like to provide a -l/--list option with nargs='?' that will change the behaviour of the program from its main function to one of giving information about all possibilities in a set or about one particular possibility.

Normally there will be a namespace attribute that contains a function to be called after parsing; I would like the -l option to both change this attribute and optionally store its argument in a different attribute.

Is this possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

终陌 2024-09-17 05:48:37

只需实现您自己的 Action 子类即可。基本上如下所示:

class ListAction(argparse.Action):
    def __call__(parser, namespace, values, option_string=None):
        setattr(namespace, 'list', values[0])
        do_something_completely_different()

argparse 文档提供了更多详细信息。

Simply implement your own Action subclass. This basically looks like this:

class ListAction(argparse.Action):
    def __call__(parser, namespace, values, option_string=None):
        setattr(namespace, 'list', values[0])
        do_something_completely_different()

The argparse documentation has more details.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文