python:组合位置和可选参数时argparse抛出值错误

时间:2017-01-03 15:24:07

标签: python-2.7 exception argparse

我试图在python中使用argparse库来读取可选和必需的参数。到目前为止,我这样做了:

import argparse
parser = argparse.ArgumentParser(description='Cleanup Script for Folder')

parser.add_argument('PATH_TO_WORKDIR_ROOT', type=str, dest='PATH_TO_WORKDIR_ROOT', action='store', help='(absolute or) relative path to directory \n   to work on, e.g. "..\MyFolder\\"')
parser.add_argument('--PATH_TO_BACKUP_ROOT', type=str, dest='PATH_TO_BACKUP_ROOT', action='store', help='(absolute or) relative path to Backup-Directory \n   default is ".\BACKUP\"')

args = parser.parse_args()

现在我正在测试我的代码,它给了我一个我不理解的价值错误:

$ python argparsetest.py --help
Traceback (most recent call last):  
File "argparsetest.py", line 5, in <module>
    parser.add_argument('PATH_TO_WORKDIR_ROOT', type=str, dest='PATH_TO_WORKDIR_ ROOT', action='store', help='(absolute or)
relative path to directory \n   to wo rk on, e.g. "..\MyFolder\\"')  
File "C:\Program
Files\Enthought\Canopy\App\appdata\canopy-1.3.0.1715.win-x86_
64\lib\argparse.py", line 1262, in add_argument
    raise ValueError('dest supplied twice for positional argument') ValueError: dest supplied twice for positional argument

只有一个位置参数,不存在且目的地不同。我真的不明白这个麻烦:)

提前多多感谢!

1 个答案:

答案 0 :(得分:8)

请查看 argparse.py 中的以下代码:

# =======================
# Adding argument actions
# =======================
def add_argument(self, *args, **kwargs):
    """
    add_argument(dest, ..., name=value, ...)
    add_argument(option_string, option_string, ..., name=value, ...)
    """

    # if no positional args are supplied or only one is supplied and
    # it doesn't look like an option string, parse a positional
    # argument
    chars = self.prefix_chars
    if not args or len(args) == 1 and args[0][0] not in chars:
        if args and 'dest' in kwargs:
            raise ValueError('dest supplied twice for positional argument')
        kwargs = self._get_positional_kwargs(*args, **kwargs)

由于您没有--到PATH_TO_WORKDIR_ROOT之前,它认为第一个参数是dest,因此当您再次提供dest作为命名参数时会引发错误。