Skip to content

Commit bc63533

Browse files
serhiy-storchakamiss-islington
authored andcommitted
pythongh-53780: Ignore the first "--" (double dash) between an option and command in argparse (pythonGH-124275)
(cherry picked from commit c578271) Co-authored-by: Serhiy Storchaka <[email protected]>
1 parent 1366fff commit bc63533

File tree

3 files changed

+23
-4
lines changed

3 files changed

+23
-4
lines changed

Lib/argparse.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2107,11 +2107,15 @@ def consume_positionals(start_index):
21072107
# and add the Positional and its args to the list
21082108
for action, arg_count in zip(positionals, arg_counts):
21092109
args = arg_strings[start_index: start_index + arg_count]
2110-
# Strip out the first '--' if it is not in PARSER or REMAINDER arg.
2111-
if (action.nargs not in [PARSER, REMAINDER]
2112-
and arg_strings_pattern.find('-', start_index,
2110+
# Strip out the first '--' if it is not in REMAINDER arg.
2111+
if action.nargs == PARSER:
2112+
if arg_strings_pattern[start_index] == '-':
2113+
assert args[0] == '--'
2114+
args.remove('--')
2115+
elif action.nargs != REMAINDER:
2116+
if (arg_strings_pattern.find('-', start_index,
21132117
start_index + arg_count) >= 0):
2114-
args.remove('--')
2118+
args.remove('--')
21152119
start_index += arg_count
21162120
take_action(action, args)
21172121

Lib/test/test_argparse.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5536,6 +5536,20 @@ def test_subparser(self):
55365536
"invalid choice: '--'",
55375537
parser.parse_args, ['--', 'x', '--', 'run', 'a', 'b'])
55385538

5539+
def test_subparser_after_multiple_argument_option(self):
5540+
parser = argparse.ArgumentParser(exit_on_error=False)
5541+
parser.add_argument('--foo', nargs='*')
5542+
subparsers = parser.add_subparsers()
5543+
parser1 = subparsers.add_parser('run')
5544+
parser1.add_argument('-f')
5545+
parser1.add_argument('bar', nargs='*')
5546+
5547+
args = parser.parse_args(['--foo', 'x', 'y', '--', 'run', 'a', 'b', '-f', 'c'])
5548+
self.assertEqual(NS(foo=['x', 'y'], f='c', bar=['a', 'b']), args)
5549+
self.assertRaisesRegex(argparse.ArgumentError,
5550+
"invalid choice: '--'",
5551+
parser.parse_args, ['--foo', 'x', '--', '--', 'run', 'a', 'b'])
5552+
55395553

55405554
# ===========================
55415555
# parse_intermixed_args tests
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
:mod:`argparse` now ignores the first ``"--"`` (double dash) between an option and command.

0 commit comments

Comments
 (0)