23.03.2021 20:00, Paolo Bonzini wrote:
On 23/03/21 17:43, Vladimir Sementsov-Ogievskiy wrote:
Interesting that REMAINDER documentation disappeared from latest (3.9) python
documentation https://docs.python.org/3.9/library/argparse.html , but exists
here https://docs.python.org/3.8/library/argparse.html (and no mark of
deprecation)
Whoa. https://bugs.python.org/issue17050 says:
---
Since this feature is buggy, and there isn't an easy fix, we should probably
remove any mention of it from the docs. We can still leave it as an
undocumented legacy feature.
There is precedent for leaving `nargs` constants undocumented.
`argparse.PARSER` ('+...') is used by the subparser mechanism, but is not
documented. https://bugs.python.org/issue16988
---
The problematic case appears to be when you have more than one positional
argument, which is exactly the case with the 3.8 documented use of REMAINDER.
Hence the decision to drop the documentation.
However, "check" works fine because the REMAINDER argument is the only
positional argument:
$ ./check 001 -d
Test "tests/-d" is not found
Another possibility is to pre-process sys.argv like this:
if '--' in sys.argv:
cmd = True
args = sys.argv[0:sys.argv.index('--')]
posargs = sys.argv[len(args)+1:]
else:
cmd = False
args = list(x for x in sys.argv if x.startswith('-'))
posargs = list(x for x in sys.argv if not x.startswith('-'))
But getting the help message right etc. would be messy.
Paolo
Hmm:
If you have positional arguments that must begin with - and don’t look like
negative numbers, you can insert the pseudo-argument '--' which tells
parse_args() that everything after that is a positional argument:
So, as I understand argparse supports '--' feature out of the box. So, we can
keep '*' as is, and it would parse all remaining positional arguments which are
either tests or the command, and '--' will be automatically dropped. So, we
only need to check existing of '--' in original sys.argv to chose our behavior.
--
Best regards,
Vladimir