#python #python-3.x
#python #python-3.x
Вопрос:
Я играю с ‘argparse’ и не могу заставить две определенные группы (sg и dg) работать одновременно.
import argparse
import os
parser = argparse.ArgumentParser(
description="Output contents of Spreadsheet into Data Structures or Render jinja2 template"
)
parser.add_argument('-v', '--verbose', action='store_true', help='Output to terminal only (Default)')
ss_args = parser.add_argument_group('Spreadsheet Options', 'Modify options for opening spreadsheet')
ss_args.add_argument('-f', '--input_file', type=str, metavar='', required=True,
help="Spreadsheet Input File (e.g. 'configs.xlsx') - (Required)")
ss_args.add_argument('-i', '--index', type=str, metavar='', help="Index of Datasets from Spreadsheet")
ss_args.add_argument('-sh', '--sheet', type=str, metavar='', help="Specify Sheet in Excel File to use")
ss_args.add_argument('-T', '--transposed', action='store_true',
help="Spreadsheet is Transposed (i.e. Column per device)")
sg = parser.add_argument_group('Saving Options', 'Output Saving Options (JSON/YAML Only)')
save_group = sg.add_mutually_exclusive_group()
save_group.add_argument('-S', '--save', action='store_true',
help='Save JSON/YAML configurations per device to file')
save_group.add_argument('-s', '--savecompiled', action='store_true',
help='Save JSON/YAML configurations per device to file')
dg = parser.add_argument_group('Data Structures', 'Output Data Structure Options')
data_group = dg.add_mutually_exclusive_group()
data_group.add_argument('-j', '--json', action='store_true', help="Output as JSON (Default)")
data_group.add_argument('-y', '--yaml', action='store_true', help="Output as YAML")
data_group.add_argument('-t', '--template', type=str, metavar='', help="Specify jinja2 template")
arguments = parser.parse_args()
Когда я запускаю код, я получаю assertionerror:
Traceback (most recent call last):
File "spreadsheet_to_data.py", line 56, in <module>
arguments = parser.parse_args()
File "C:UsersAppDataLocalProgramsPythonPython36libargparse.py", line 1730, in parse_args
args, argv = self.parse_known_args(args, namespace)
File "C:UsersAppDataLocalProgramsPythonPython36libargparse.py", line 1762, in parse_known_args
namespace, args = self._parse_known_args(args, namespace)
File "C:UsersAppDataLocalProgramsPythonPython36libargparse.py", line 1968, in _parse_known_args
start_index = consume_optional(start_index)
File "C:UsersAppDataLocalProgramsPythonPython36libargparse.py", line 1908, in consume_optional
take_action(action, args, option_string)
File "C:UsersAppDataLocalProgramsPythonPython36libargparse.py", line 1836, in take_action
action(self, namespace, argument_values, option_string)
File "C:UsersAppDataLocalProgramsPythonPython36libargparse.py", line 1020, in __call__
parser.print_help()
File "C:UsersAppDataLocalProgramsPythonPython36libargparse.py", line 2362, in print_help
self._print_message(self.format_help(), file)
File "C:UsersAppDataLocalProgramsPythonPython36libargparse.py", line 2346, in format_help
return formatter.format_help()
File "C:UsersAppDataLocalProgramsPythonPython36libargparse.py", line 282, in format_help
help = self._root_section.format_help()
File "C:UsersAppDataLocalProgramsPythonPython36libargparse.py", line 213, in format_help
item_help = join([func(*args) for func, args in self.items])
File "C:UsersAppDataLocalProgramsPythonPython36libargparse.py", line 213, in <listcomp>
item_help = join([func(*args) for func, args in self.items])
File "C:UsersAppDataLocalProgramsPythonPython36libargparse.py", line 333, in _format_usage
assert ' '.join(opt_parts) == opt_usage
AssertionError
Если я закомментирую одну из групп ‘sg’ или ‘dg, она работает нормально.
usage: spreadsheet_to_data.py [-h] [-v] -f [-i] [-sh] [-T] [-j | -y | -t ]
Output contents of Spreadsheet into Data Structures or Render jinja2 template
optional arguments:
-h, --help show this help message and exit
-v, --verbose Output to terminal only (Default)
Spreadsheet Options:
Modify options for opening spreadsheet
-f , --input_file Spreadsheet Input File (e.g. 'configs.xlsx') -
(Required)
-i , --index Index of Datasets from Spreadsheet
-sh , --sheet Specify Sheet in Excel File to use
-T, --transposed Spreadsheet is Transposed (i.e. Column per device)
Data Structures:
Output Data Structure Options
-j, --json Output as JSON (Default)
-y, --yaml Output as YAML
-t , --template Specify jinja2 template
Кажется, я просто не могу заставить оба работать одновременно — есть предложения?
Заранее спасибо!
Комментарии:
1. Когда вы говорите «запустите его», как вы вызываете программу из командной строки? Если я скопирую-вставлю этот код, добавлю
print(arguments)
внизу и выполню его либо с--help
помощью, либо с-f blah
помощью, я не получаю ошибок в Python 3.7 (Windows или macOS).2. На самом деле предоставленный вами код отлично работает в Python 3.6 trinket.io/python3/d41f438371?showInstructions=true
3. Какова ваша точная версия python?
4. В Python 3.6 argparse была исправлена ошибка: github.com/python/cpython/pull/7528 слияние в июне 2018 года — если ваш python старше — это, скорее всего, причина.
5. Приветствую всех. Я был в Python 3.6.2 и, похоже, это была ошибка. Пробовал в других версиях и ок. Приветствую всех.