python argparse同时预防长标志

发布于 2025-01-28 19:51:20 字数 393 浏览 0 评论 0原文

我有这个代码:

parser = argparse.ArgumentParser()
parser.add_argument('-L', '--list', action='store_true', help='list options')
args = parser.parse_args()

我想要这样的:

$./example.py --list

或者

$./example.py -L

不:

$./example -L --list # or --list -L

有没有一种优雅的方法来避免同时使用两个标志?

I have this code:

parser = argparse.ArgumentParser()
parser.add_argument('-L', '--list', action='store_true', help='list options')
args = parser.parse_args()

I want this:

$./example.py --list

or

$./example.py -L

but not:

$./example -L --list # or --list -L

Is there an elegant way to avoid that both flags being used at the same time?

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

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

发布评论

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

评论(1

淡紫姑娘! 2025-02-04 19:51:20

您可以组成一个互斥的群体。这不是理想的选择,因为您最终会重复每个参数,但是如果需要,可以将其包裹到助手功能中。

parser = argparse.ArgumentParser()

arg_group = parser.add_mutually_exclusive_group()
arg_group.add_argument('-L', action='store_true', help='list options')
arg_group.add_argument('--list', action='store_true', help='list options')

args = parser.parse_args()

如果您想稍微漂亮一点(避免重复自己),则可以做类似的事情:

class MutexArgParser(argparse.ArgumentParser):
    def add_mutex_arguments(self, flags, *args, **kwargs):
        arg_group = self.add_mutually_exclusive_group()
        for flag in flags:
            arg_group.add_argument(flag, *args, **kwargs)

parser = MutexArgParser()
parser.add_mutex_arguments(['-L', '--list'], action='store_true', help='list options')
args = parser.parse_args()

You can form a mutually exclusive group. That isn't ideal, since you'll end up repeating arguments to each, but that can be wrapped up into a helper function if need be.

parser = argparse.ArgumentParser()

arg_group = parser.add_mutually_exclusive_group()
arg_group.add_argument('-L', action='store_true', help='list options')
arg_group.add_argument('--list', action='store_true', help='list options')

args = parser.parse_args()

If you wanted to pretty this up a bit (to avoid repeating yourself), you could do something like:

class MutexArgParser(argparse.ArgumentParser):
    def add_mutex_arguments(self, flags, *args, **kwargs):
        arg_group = self.add_mutually_exclusive_group()
        for flag in flags:
            arg_group.add_argument(flag, *args, **kwargs)

parser = MutexArgParser()
parser.add_mutex_arguments(['-L', '--list'], action='store_true', help='list options')
args = parser.parse_args()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文