在 Python 3.2 上设置 argparse

发布于 2025-01-08 14:26:35 字数 1999 浏览 0 评论 0原文

我正在尝试在我的 python 程序上设置 argparse 但它不起作用。 我尝试处理的参数如下:

第一个参数为“--interactive”或整数,其中一个是必需的

“--xml”或“--html”或“--”中的任何一个文本'或'--控制台'。同样,它可以是其中任何一个,但第二个参数需要其中之一

,最后对于第三个参数,“--verbose”标志是可选的。

除了第一个参数的整数之外,所有这些参数都将变量更改为 True。

这是我目前的代码:

import argparse

parser = argparse.ArgumentParser(description='Python Historical Event Calculator.',
                             prog='tempus.py')

inputs = parser.add_mutually_exclusive_group(required=True)
exports = parser.add_mutually_exclusive_group(required=True)

inputs.add_argument('integer', metavar='I', type=float,
               help='percentage to use')

inputs.add_argument('-i','--interactive', dest='bool_interactive', 
               action='store_true', help='enter interactive mode')

exports.add_argument('-x','--xml', dest='bool_xml', action='store_true',
               help='export output as xml')

exports.add_argument('--html', dest='bool_html', action='store_true',
               help='export output as html')

exports.add_argument('-t','--text', dest='bool_text', action='store_true',
               help='export output as plaintext')

exports.add_argument('-c','--console', dest='bool_con', action='store_true',
               help='export output to console')

parser.add_argument('-v','--verbose', dest='verbose', action='store_true',
               help='enter verbose/debug mode', required=False)

args = parser.parse_args()

但我不知道我是否走在正确的轨道上,有人可以帮忙吗?这看起来是对的还是我完全错了?

编辑

当我向它传递任何标志时,我会得到这个回溯:

Traceback (most recent call last):
  File "C:\Users\Callum\Dropbox\Tempus\Feature Tests\argparsetest.py", line 9, in <module>
    help='percentage to use')
  File "C:\Python32\lib\argparse.py", line 1305, in add_argument
    return self._add_action(action)
  File "C:\Python32\lib\argparse.py", line 1528, in _add_action
    raise ValueError(msg)
ValueError: mutually exclusive arguments must be optional

I'm trying to set up argparse on my python program but it's not working.
The arguments I'm trying to process are as follows:

Either '--interactive' OR an integer for the first argument, one of these is required

Any one of either '--xml' OR '--html' OR '--text' OR '--console'. Again, it can be any one of these but one of them is required for the second argument

And finally for the third argument, a '--verbose' flag which is optional.

All of these arguments change variables to True, apart from the integer on the first argument.

This is the code I have at the minute:

import argparse

parser = argparse.ArgumentParser(description='Python Historical Event Calculator.',
                             prog='tempus.py')

inputs = parser.add_mutually_exclusive_group(required=True)
exports = parser.add_mutually_exclusive_group(required=True)

inputs.add_argument('integer', metavar='I', type=float,
               help='percentage to use')

inputs.add_argument('-i','--interactive', dest='bool_interactive', 
               action='store_true', help='enter interactive mode')

exports.add_argument('-x','--xml', dest='bool_xml', action='store_true',
               help='export output as xml')

exports.add_argument('--html', dest='bool_html', action='store_true',
               help='export output as html')

exports.add_argument('-t','--text', dest='bool_text', action='store_true',
               help='export output as plaintext')

exports.add_argument('-c','--console', dest='bool_con', action='store_true',
               help='export output to console')

parser.add_argument('-v','--verbose', dest='verbose', action='store_true',
               help='enter verbose/debug mode', required=False)

args = parser.parse_args()

But I have no idea if I'm on the right track with this though, can anyone help? Does this look about right or have I done it completely wrong?

Edit

I get this traceback when I pass any flag to it:

Traceback (most recent call last):
  File "C:\Users\Callum\Dropbox\Tempus\Feature Tests\argparsetest.py", line 9, in <module>
    help='percentage to use')
  File "C:\Python32\lib\argparse.py", line 1305, in add_argument
    return self._add_action(action)
  File "C:\Python32\lib\argparse.py", line 1528, in _add_action
    raise ValueError(msg)
ValueError: mutually exclusive arguments must be optional

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

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

发布评论

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

评论(2

韵柒 2025-01-15 14:26:35

您的错误,ValueError:互斥参数必须是可选的,是因为您将整数(位置参数)添加到互斥组中而发生的。互斥组仅适用于可选参数,而位置参数始终是必需的。一种解决方案是使交互式参数和整数可选参数都成为可选参数,并使它们互斥。

我最初错过了这样一个事实:您在模式上使用了 mutually_exclusive_group,因此仅指定了 xml、html、控制台或文本,但如果您确实喜欢这个想法,我确实对其进行了更改。

这个解析器可以工作,它使您的 interactiveinteger 参数互斥,并使模式成为 选择列表

#!/usr/bin/env python

import argparse

def get_parser():
    parser = argparse.ArgumentParser(prog='tempus.py')
    ex_group = parser.add_mutually_exclusive_group(required=True)
    parser.add_argument('--mode', type=str, choices=['html', 'xml', 'text', 'console'], required=True)
    parser.add_argument('-v', '--verbose', action='store_true')
    ex_group.add_argument('--interactive', action='store_true')
    ex_group.add_argument('--integer', metavar='I', type=float, help='percentage to use')
    return parser

def main():
    aparser = get_parser()
    args = aparser.parse_args()

    print('mode: %s' % args.mode)
    print('integer: %s' % args.integer)
    print('interactive: %s' % args.interactive)
    print('verbose: %s' % args.verbose)

# Only used in Python 2.x
if __name__ == '__main__':
    main()

示例运行:

+> python .\tempus.py
usage: tempus.py [-h] --mode {html,xml,text,console} [-v]
                 (--interactive | --integer I)
tempus.py: error: argument --mode is required

+> python .\tempus.py --mode html
usage: tempus.py [-h] --mode {html,xml,text,console} [-v]
                 (--interactive | --integer I)
tempus.py: error: one of the arguments --interactive --integer is required

+> python .\tempus.py --mode html --integer
usage: tempus.py [-h] --mode {html,xml,text,console} [-v]
                 (--interactive | --integer I)
tempus.py: error: argument --integer: expected one argument

+> python .\tempus.py --mode html --integer 12
mode: html
integer: 12.0
interactive: False
verbose: False

Your error, ValueError: mutually exclusive arguments must be optional, happened because you are adding integer (a positional argument), to a mutually exclusive group. Mutually exclusive groups are only for optional arguments, whereas positional arguments are always required. One solution is to make both interactive and integer optional arguments, and mutually exclusive them.

I originally missed the fact that you used a mutually_exclusive_group on your modes, so that only xml, html, console, or text were specified, but I did change it up if you do like that idea.

This parser would work, it makes your interactive and integer arguments mutually exclusive, and makes mode a choice list.

#!/usr/bin/env python

import argparse

def get_parser():
    parser = argparse.ArgumentParser(prog='tempus.py')
    ex_group = parser.add_mutually_exclusive_group(required=True)
    parser.add_argument('--mode', type=str, choices=['html', 'xml', 'text', 'console'], required=True)
    parser.add_argument('-v', '--verbose', action='store_true')
    ex_group.add_argument('--interactive', action='store_true')
    ex_group.add_argument('--integer', metavar='I', type=float, help='percentage to use')
    return parser

def main():
    aparser = get_parser()
    args = aparser.parse_args()

    print('mode: %s' % args.mode)
    print('integer: %s' % args.integer)
    print('interactive: %s' % args.interactive)
    print('verbose: %s' % args.verbose)

# Only used in Python 2.x
if __name__ == '__main__':
    main()

Sample run:

+> python .\tempus.py
usage: tempus.py [-h] --mode {html,xml,text,console} [-v]
                 (--interactive | --integer I)
tempus.py: error: argument --mode is required

+> python .\tempus.py --mode html
usage: tempus.py [-h] --mode {html,xml,text,console} [-v]
                 (--interactive | --integer I)
tempus.py: error: one of the arguments --interactive --integer is required

+> python .\tempus.py --mode html --integer
usage: tempus.py [-h] --mode {html,xml,text,console} [-v]
                 (--interactive | --integer I)
tempus.py: error: argument --integer: expected one argument

+> python .\tempus.py --mode html --integer 12
mode: html
integer: 12.0
interactive: False
verbose: False
多像笑话 2025-01-15 14:26:35

integer 更改为可选的 positional

inputs.add_argument('integer', nargs='?', metavar='I', type=float, ...)

这样,-i33 都会被 接受>inputs 组,-i 33 不会。

Change integer to be an optional positional

inputs.add_argument('integer', nargs='?', metavar='I', type=float, ...)

With this, -i and 33 would both be accepted by the inputs group, -i 33 would not.

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