Mis*_*cht 7 exception python-2.7 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()
Run Code Online (Sandbox Code Playgroud)
现在我正在测试我的代码,它给了我一个我不理解的值错误:
$ 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
Run Code Online (Sandbox Code Playgroud)
只有一个位置参数,不存在且目的地不同.我真的不明白麻烦:)
非常感谢提前!
Mot*_*ohn 12
请查看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)
Run Code Online (Sandbox Code Playgroud)
由于您没有在--PATH_TO_WORKDIR_ROOT 之前,dest因此当您dest再次作为命名参数提供时,它认为第一个参数因此引发错误.