paul j3 added the comment:
I think this problem arises from a change made in
http://bugs.python.org/issue10424
Changeset to default (i.e. development) is
http://hg.python.org/cpython/rev/cab204a79e09
Near the end of _parse_known_args it removes a:
if positionals:
self.error(_(
paul j3 added the comment:
Further observations:
parser.add_subparsers() accepts a 'dest' keyword arg, but not a 'required' one.
Default of 'dest' is SUPPRESS, so the name does not appear in the Namespace.
Changing it to something like 'command' will p
paul j3 added the comment:
This patch addresses both issues raised here:
- throw an error when the subparser argument is missing
- allow the subparser argument to be optional
argparse.py:
_SubParsersAction -
add 'required=True' keyword.
name(self) method - creates a name o
paul j3 added the comment:
This patch removes only one '--', the one that put a '-' in the
'arg_strings_pattern'. It does this in 'consume_positionals' right before
calling 'take_action'. As before it does not do this if nargs
paul j3 added the comment:
This patch permits the mixing of optionals with positionals, with the caveat
that a particular positional cannot be split up.
If:
parser = ArgumentParser()
parser.add_argument('-f','--foo')
parser.add_argument('cmd')
par
paul j3 added the comment:
It does shift the error from parse_args to add_argument, but the message
'ValueError: length of metavar tuple does not match nargs', indicates that it's
a side effect of checking on the tuple form of `metavar`.
http://bugs.python.org/issue9348
Ther
paul j3 added the comment:
I've experimented with an argparse adaptation of profile.py:
parser = argparse.ArgumentParser(usage=usage)
parser.add_argument('-o', '--outfile', dest="outfile",
help="Save stats to ", metavar="path&qu
paul j3 added the comment:
In this example:
>>> p.add_argument('--foo', nargs='*', default=None)
>>> p.parse_args([])
Namespace(foo=None)
>>> p.parse_args(['--foo'])
Namespace(foo=[])
'p.parse_args([])'
paul j3 added the comment:
The problem isn't with REMAINDER, but with the distinction between optionals
and arguments. If you change '--def' to 'def', the parse should work:
>>> p = ArgumentParser(prog='test.py')
>>> p.add_argument('re
paul j3 added the comment:
Here's a way of passing an optional-like argument to a subparser:
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest='cmd')
sub1 = subparsers.add_parser('cmd')
sub1.add_argument('foo',nargs=
paul j3 added the comment:
An alternative to Jason's example:
parser = argparse.ArgumentParser()
parser.add_argument('app')
parser.add_argument('--config')
parser.add_argument('app_args', nargs=argparse.REMAINDER)
args = parser.parse_args(['--confi
paul j3 added the comment:
By the way, parser.parse_args() uses parse_known_arg(). parse_known_args
returns a Namespace and a list of unknown arguments. If that list is empty,
parse_args returns the Namespace. If the list is not empty, parse_args raises
an error.
So parse_known_args does
paul j3 added the comment:
parser = argparse.ArgumentParser()
parser.add_argument('-k','--known',action='store_true')
print(parser.parse_known_args(['-k','-u']))
print(parser.parse_known_args(['-ku']))
print(parser.p
paul j3 added the comment:
The 'subparsers' object has a _parser_class attribute that is normally set to
the class of the parent parser. In the attached file I create a
class CustomParser(argparse.ArgumentParser)
that makes a parser instance which copies all of the att
paul j3 added the comment:
Glenn
Take a look at http://bugs.python.org/issue15427
I took a stab at changing the documentation, including recommending
parse_known_args when porting optparse uses.
--
___
Python tracker
<http://bugs.python.
Changes by paul j3 :
--
nosy: +paul.j3
___
Python tracker
<http://bugs.python.org/issue14364>
___
___
Python-bugs-list mailing list
Unsubscribe:
http://mail.pyth
paul j3 added the comment:
I submitted a patch to http://bugs.python.org/issue9253
The reason why subparser became optional in the latest release is that a old
test for missing positionals was phased out, and new one added. Subparsers
have always had a default 'required=False', b
paul j3 added the comment:
The patch that I recently submitted for http://bugs.python.org/issue13922
appears to solve this issue. It only removes the '--' that marked the end of
options.
With:
parser = argparse.ArgumentParser()
parser.add_argument('-f','--foo&
paul j3 added the comment:
The attached file has a 'parse_intermixed_args()' that has the same API as
'parse_known_args()'.
It follows the two parse step model
args, remaining_args = optionals.parse_known_args()
args, extras = positionals.parse_known_args(remaining
paul j3 added the comment:
This nargs test using the formater applies only when the container has a help
formatter. That is true for a ArgumentParser, but not for an argument_group.
group = parser.add_argument_group('g')
group.add_argument('bar', nargs='test
paul j3 added the comment:
Yes, http://bugs.python.org/msg166175 does use 'parse_args' in the second call.
But I think things would be more flexible if we had a second function:
def parse_???(self, args=None, namespace=None):
args, argv = self.parse_intermixed_args(args,
paul j3 added the comment:
This patch adds a value test for nargs during add_argument. The core of the
new test is in ArgumentParser._check_argument.
add_argument() now calls ArgumentParser._check_argument(), which calls
_format_args(). If it gets a TypeError, it raises a metavar ValueError
paul j3 added the comment:
The attached test_nargswarn.py file tests the argparse.py patch. It tries out
various nargs values, both for parsers, groups, and mutually exclusive groups.
I intend to recast these to work in test_argparse.py
--
Added file: http://bugs.python.org
paul j3 added the comment:
This is a revision of yesterday's patch. It includes a couple of test cases
that check that parser, groups, and exclusive groups all produce the error
message.
I also changed the metavar tuple case to return an ArgumentError, and changed
test_argpar
paul j3 added the comment:
http://bugs.python.org/issue9849
also deals with nargs values. However there the focus is on string values like
'1', not whether an integer value can be 0 or <0.
I submitted a patch that moves the nargs testing to a
ArgumentParser._check_argument(
paul j3 added the comment:
An integer nargs value is only used in one of 2 ways,
range(nargs)
'%s'*nargs
In both a negative value acts the same as a 0.
I don't think the original authors though much about 'what if the code user
gives a negative value?', because
paul j3 added the comment:
Correction: The patch I gave in the last message produces:
>>> parser.parse_known_args(['-ku'])
(Namespace(known=False), ['u'])
It doesn't take action on the '-k', and puts 'u
paul j3 added the comment:
Looks like the
text = text.strip()
at the end of the set of regex (in _format_actions_usage) needs to be replaced
with something that removes all excess spaces, e.g.
text = _re.sub( '\s+', ' ', text ).strip()
-
paul j3 added the comment:
In the test case: class TestMutuallyExclusiveManySuppressed
even with a short 'eggs' argument, there is a difference
Old usage would be:
usage: PROG [-h] [--eggs EGGS]
new
usage: PROG [-h] [--eggs EGGS]
i.e. 2 v 1 space. But extra spaces are not as
paul j3 added the comment:
I see three solutions -
1) gholms' patch which removes '() ' and [] '
2) Yogesh's patch which removes all duplicated spaces.
3) remove the 2 asserts.
The first 2 do the same thing most of the time, but may differ if the user
somehow
paul j3 added the comment:
This is a revision of the test_intermixed.py that I submitted earlier. Now
`parse_intermixed_args` acts like `parse_args', and calls
`parse_known_intermixed_args`. Again it is form that can exercise the idea
without modifying `argparse.py`.
If the parse
paul j3 added the comment:
This is the formal patch corresponding to the `test_intermixed.py`. It
includes changes to `argparse.rst`, plus tests in `test_argparse.py`. These
tests are near the end, after those for `parse_known_args`. They are roughly
equivalent to the examples in
paul j3 added the comment:
Wouldn't it be simpler to use the re {m,n} notation to grab the appropriate
number of arguments?
In ArgumentParser _get_nargs_pattern we could add:
+# n to m arguments, nargs is re like {n,m}
+elif is_mnrep(nargs):
+nargs_pa
paul j3 added the comment:
I think this patch should build on http://bugs.python.org/issue9849, which
seeks to improve the error checking for nargs. There, add_argument returns an
ArgumentError if the nargs value is not a valid string, interger, or it there
is mismatch between a tuple
paul j3 added the comment:
This patch adds this `nargs='{m,n}'` or `nargs=(m,n)` feature.
It builds on the `better nargs error message` patch in
http://bugs.python.org/msg187754
It includes an argparse.rst paragraph, changes to argparse.py, and additions to
test_argparse.py.
paul j3 added the comment:
'parse_fallback_args()' function is only in the 'test_intermixed.py' file, not
the patch. It should be in the 'if __name__' section of that file, along with
the modified 'exit()' method, since it is part of these
paul j3 added the comment:
I should note one caveat:
As a consequence of setting nargs to 0 for the first 'parse_know_args' step,
all positional entries in the namespace get an empty list value ([]). This is
produced by 'ArgumentParser._get_values'. With the builtin
paul j3 added the comment:
I'm following a dozen argparse issues with patches. I haven't seen much
posting by argparse experts (like bethard, david.murry) since last December.
--
___
Python tracker
<http://bugs.python.o
paul j3 added the comment:
I was wondering about that block of code earlier.
It would be a good idea to look at what func() does, just to make sure there
aren't any side effects - e.g. set maximum line length, required indention, etc.
--
nosy: +pa
New submission from paul j3:
"16.4.3.11. dest
For optional argument actions,... Any internal - characters will be converted
to _ characters to make sure the string is a valid attribute name."
In _get_optional_kwargs(), dest = dest.replace('-', '_'); but
Changes by paul j3 :
--
nosy: +paul.j3
___
Python tracker
<http://bugs.python.org/issue14046>
___
___
Python-bugs-list mailing list
Unsubscribe:
http://mail.pyth
Changes by paul j3 :
--
nosy: +paul.j3
___
Python tracker
<http://bugs.python.org/issue9338>
___
___
Python-bugs-list mailing list
Unsubscribe:
http://mail.pyth
Changes by paul j3 :
Removed file: http://bugs.python.org/file29880/mixed.patch
___
Python tracker
<http://bugs.python.org/issue14191>
___
___
Python-bugs-list mailin
Changes by paul j3 :
--
title: argparse does not dest.replace('-', '_') for postionals -> argparse
does not dest.replace('-', '_') for positionals
___
Python
paul j3 added the comment:
I've played a bit the idea that barthard sketched. I don't have all the
details worked out, but I believe this is what will happen:
With
parser = argparse.ArgumentParser()
parser.add_argument('-w')
parser.add_argument('-x', nargs
paul j3 added the comment:
I need to make one correction to my last post:
'-x 1 2 -w 3 4 5 6', # w:3, x:[1,2], y:4, z:[5,6] +
# w:3, x:[1], y:2, z:[4,5,6] -
The second solution is only possible if 'z' is not consumed when 'y' is
paul j3 added the comment:
This patch implements, I think, the ideas bethard proposed. It is test patch,
not intended for production.
Most of work is in ArgumentParser._get_alt_length() which
- generates a pattern along the lines bethard proposed
- generates a string like arg_strings_pattern
paul j3 added the comment:
This is a test file for the patch I just submitted.
It is not a formal unitttest, but uses print output as much as assert.
Cases include the example bethard used, as well as ones from test_argparse.py
that initially caused problems.
--
Added file: http
paul j3 added the comment:
Here's another approach to the problem, using an iterative localized search.
For simple cases it produces the same thing, but in complex cases it is more
robust.
It is based on two ideas:
- if the action in consume_optional() is being 'greedy',
Changes by paul j3 :
Removed file: http://bugs.python.org/file30349/argparse_7.py
___
Python tracker
<http://bugs.python.org/issue9338>
___
___
Python-bugs-list mailin
paul j3 added the comment:
Oops, I attached the wrong file. Here's the correct one.
--
Added file: http://bugs.python.org/file30350/issue9338_7.patch
___
Python tracker
<http://bugs.python.org/i
paul j3 added the comment:
In the attached patch I modified 'add_parser' to take a 'parser' keyword
parameter. If given, it is used as the parser, rather than create a new one.
Thus an existing parser, or one created with a custom ArgumentParser class,
could be used a
paul j3 added the comment:
A possible problem with this patch is that it overrides any Namespace given by
the user. In the test example:
parser.parse_args(['X'], namespace=argparse.Namespace(foo=3))
the result is 'foo=2', the setdefault from the subparser. Previously
paul j3 added the comment:
This issue has already been raise in
http://bugs.python.org/issue9334
argparse does not accept options taking arguments beginning with dash
(regression from optparse)
There I proposed leaving '_negative_number_matcher' unchanged, but only use
paul j3 added the comment:
Patch tests are added to an existing 'Lib/test/test_argparse.py' file. I use
existing test cases as a pattern any new tests.
-
Your test file runs fine with the patch I proposed for Issue 9334.
-
The argparse
paul j3 added the comment:
I'm exploring modifying that patch by adding a 'subnamespace' attribute to the
subparsers Action object. This would give the user, or the main parser control
over the namespace that is passed to a subparser.
For example:
subnamespace
paul j3 added the comment:
The patch with a major rewrite of '_format_actions_usage' handles this usage
problem correctly:
usage: try_para_in_meta.py [-h] input_file(s) [input_file(s) ...]
The error is the result of usage group formatter trying to remove excess `()`.
To give
paul j3 added the comment:
A notational point - you are adding a subparser, not an argument, to the
subparsers action.
Why would a user want to use `help=argparse.SUPPRESS`, as opposed to simply
omitting the `help` parameter? The effect would be the same as your patch.
Another
paul j3 added the comment:
Related issues are:
http://bugs.python.org/issue13824 - argparse.FileType opens a file and never
closes it
http://bugs.python.org/issue14156 - argparse.FileType for '-' doesn't work for
a mode of 'rb'
As discussed earlier FileType was m
paul j3 added the comment:
This an issue for parse_args as well. parse_args just calls parse_known_args,
and raises an error if extras is not empty.
Early on in parsing, it tries to classify argument strings as either optionals
(--flags) or positionals (arguments). And there's an exp
paul j3 added the comment:
Duplicate of
http://bugs.python.org/issue22433
--
resolution: -> duplicate
___
Python tracker
<http://bugs.python.org/issu
paul j3 added the comment:
And the corresponding bug issue
http://bugs.python.org/issue9351
--
nosy: +paul.j3
___
Python tracker
<http://bugs.python.org/issue24
paul j3 added the comment:
Another example of this patch causing backward compatibility problems
http://bugs.python.org/issue24251
--
___
Python tracker
<http://bugs.python.org/issue9
paul j3 added the comment:
The code that converts '-' to '_' is independent of the code that uses
'prefix_chars'.
The '-' conversion handles a long standing UNIX practice of allowing that
character in the middle of option flags. It's an attempt
paul j3 added the comment:
Off hand I don't see a problem with this patch (but I haven't tested it yet).
But I have a couple of cautions:
The docs say, regarding the Namespace class:
> This class is deliberately simple, just an object subclass with a readable
> string repre
paul j3 added the comment:
An alternative would be to wrap a non-identifier name in 'repr()':
def repr1(self):
def fmt_name(name):
if name.isidentifier():
return name
else:
return repr(name)
type_name =
paul j3 added the comment:
http://bugs.python.org/issue15125
argparse: positional arguments containing - in name not handled well
Discussion on whether positionals 'dest' should translate '-' to '_'.
--
___
Python tr
paul j3 added the comment:
Yes, the '_' makes it accessible as an attribute name. But the presence of '-'
in the option name has a UNIX history. That is a flag like '--a-b-c' is
typical, '--a_b_c' is not.
There is less of precedent for a flag like
paul j3 added the comment:
I mentioned in the related bug/issue that no one has to use odd characters and
spaces in the Namespace. While they are allowed by 'getattr' etc, the
programmer has the option of supplying rational names in the 'dest' parameter.
There's
paul j3 added the comment:
Does this work for
help='choices: %(choices)s'
Without setting up my own test case, I'm guessing that the problem is with an
empty help string. `help=''` should be ok, but the test handle that probably
occurs earlier.
Choices, e
Changes by paul j3 :
--
nosy: +paul.j3
___
Python tracker
<http://bugs.python.org/issue24441>
___
___
Python-bugs-list mailing list
Unsubscribe:
https://mail.pyth
paul j3 added the comment:
What are you trying to accomplish in the examples with a 'dest'? For a
positional, 'dest' is derived from the 'foo' name. There is no need to supply
'dest', in fact produces the error you get. It has nothing to with
paul j3 added the comment:
None of the `append` actions makes sense with positionals. The name (and hence
the 'dest') must be unique. And positionals can't be repeated.
There are other ways to put a pair of values in the Namespace. For example,
after parsing
args.x
paul j3 added the comment:
You can give the positional any custom name (the first parameter). You just
can't reuse it (by giving 2 positionals the same name). And if you don't like
what the 'help' shows, you can set the 'metavar'. That way only you see the
pos
paul j3 added the comment:
(Important correction at the end of this post)
The test that you are complaining about occurs at the start of the
'add_argument' method:
def add_argument(self, *args, **kwargs):
"""
add_argument(dest, ..., name=value,
paul j3 added the comment:
To wrap this up, the correct way to specify that 2 or more positionals share a
'dest' is to supply that dest as the first parameter. If the help should have
something else, use the `metavar`.
import argparse
parser = argparse.Argu
paul j3 added the comment:
Right, the only arguments that a `store_true` Action class accepts are:
option_strings, dest, default=False,required=False, help=None
parser.add_argument() massages its parameters a bit, and then uses the 'action'
parameter to construct an Actio
paul j3 added the comment:
argparse.FileType serves 2 purposes
- handling filenames for simple quick shell-like scripts
- as a model for custom 'types', specifically one that uses a class to generate
the desired type callable.
Other bug-issues show that it hasn't aged well.
paul j3 added the comment:
These two types of groups serve different purposes and aren't designed to nest
or interact.
An argument group groups arguments in the help lines. It does not affect
parsing at all. It can't be used to add a 'group' of arguments to another
paul j3 added the comment:
Also, argparse.PARSER is '+...'
'? * +' have closely matched analogs in regex patterns. '...' and '+...' do
not. So Python users will have an intuitive idea of what "nargs='*'" means.
"nargs=
paul j3 added the comment:
A related issue which Sworddragon found just before starting this issue is
http://bugs.python.org/issue9625
The handling of defaults in argparse is a bit complicated. In general it errs
on the side of giving the user/developer freedom to set them how ever they
paul j3 added the comment:
`parser.set_defaults` lets you set a default for any `dest`. It does not have
to be connected with an argument. See what the docs say about using it to set
an action linked to a subparser.
`arg1 = parser.add_argument(...)` returns an `Action` object. The parser
paul j3 added the comment:
`get_default` and `set_defaults` are parser methods, and do more than set or
get a particular Action attribute. 'Set' for example changes both the
'parser._defaults' attribute, and a 'action.default' attribute. Defaults are
complex an
paul j3 added the comment:
This assertion error caused by brackets (and other 'odd' characters) in the
metavar is a known issue.
http://bugs.python.org/issue11874
http://bugs.python.org/issue14046
The formatter that handles line wrapping of the usage line is fragile.
-
paul j3 added the comment:
The `type` parameter is a *function* that takes a string, and returns a valid
value. If it can't convert the string it is supposed to raise an error. The
default one is a do-nothing identity (take a string, return the string). `int`
is the Python function
paul j3 added the comment:
Here's a type function that enumerates the enum in the error message:
def enumtype(astring):
try:
return CustomEnumType[astring.upper()]
except KeyError:
msg = ', '.join([t.name.lower() for t in CustomEnumType])
msg =
paul j3 added the comment:
I'm not quite sure what you mean by 'the enum type to be stored directly'.
With my type function, the string input is converted to an enum object and that
is stored in the Namespace. You can't be any more direct than that.
Or are you thinking
paul j3 added the comment:
Here's a EnumType factory class, modeled on FileType.
class EnumType(object):
"""Factory for creating enum object types
"""
def __init__(self, enumclass):
self.enums = enumclass
def __call__(self, astring):
paul j3 added the comment:
I realized while answering a Stackoverflow question that the resolve method has
the pieces for removing an Action from the parser. It removes an existing
Action so that the new, conflicting one, can replace it.
It's meant to be used with flagged arguments
paul j3 added the comment:
A related issue is
http://bugs.python.org/issue24754
argparse add_argument with action="store_true", type=bool should not crash
In this case the user specified a parameter that the 'store_true' subclass did
not accept.
In both cases, '
Changes by paul j3 :
--
nosy: +paul.j3
___
Python tracker
<http://bugs.python.org/issue25297>
___
___
Python-bugs-list mailing list
Unsubscribe:
https://mail.pyth
paul j3 added the comment:
My testing shows that it's a problem with the subparsers listing. When regular
arguments are long, 'max_help_position' works (within limits allowed by
'width').
--
___
Python tracker
<http:
paul j3 added the comment:
There's a bug in the HelpFormatter.add_argument method. It does not take into
account the extra indentation of subactions (sub parsers) when calculating
self._action_max_length.
The corrected method and a test case is in the attached file.
class MyForm
paul j3 added the comment:
A fix that I am exploring would wrap the Action instantiation call in
add_argument with a try/except block
That is replace:
def add_argument(...)
action = action_class(**kwargs)
...
with
try:
action
paul j3 added the comment:
The unittest file test_argparse.py tests add_argument parameters in
class TestInvalidArgumentConstructors(TestCase)
It looks at a dozen different categories of errors, mostly checking that they
return the correct TypeError or ValueError. It does not check the
paul j3 added the comment:
The unittest test_argparse.py has one related test
class TestAddSubparsers
def test_alias_help
has a long enough subparser invocation (with aliases) to produce wrapping with
the default 24 max position:
commands:
COMMAND
paul j3 added the comment:
I don't recall other issues or discussions about lining up short and long
option strings.
Producing a more compact invocation has raised in StackOverflow questions. I
don't recall if there has been bug/issue on the same.
If I recall correctly it isn
paul j3 added the comment:
http://stackoverflow.com/questions/18275023/dont-show-long-options-twice-in-print-help-from-argparse
http://stackoverflow.com/questions/9366369/python-argparse-lots-of-choices-results-in-ugly-help-output
http://stackoverflow.com/questions/23936145/python-argparse
paul j3 added the comment:
Formatter _format_action_invocation(self, action) is the key function. Notice
how it treats positionals and optionals separately. Also it calls
default = self._get_default_metavar_for_optional(action)
args_string = self._format_args(action, default)
to get
paul j3 added the comment:
I have seen questions on StackOverflow with 'store_true' and explicit
`default=False` parameters. I don't recall any where this was a problem.
Usually it's as harmless as users specifying other defaults like
`action='store'`, or a
601 - 700 of 778 matches
Mail list logo