Giter Club home page Giter Club logo

argparse's People

Contributors

thomaswaldmann avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

argparse's Issues

DeprecationWarnings in the tests for Python 2.6

What steps will reproduce the problem?
1. Run the unit tests with Python 2.6.

What is the expected output? What do you see instead?
I expect to see no DeprecationWarnings, instead three DeprecationWarnings are 
printed.

What version of the product are you using? On what operating system?
I'm using r23, on Linux, with Python 2.6.2.

Please provide any additional information below.
I've attached a patch that removes the DeprecationWarnings.  Thanks!

Original issue reported on code.google.com by [email protected] on 11 Jul 2009 at 5:03

Attachments:

%(prog)s in version string is not being replaced

What steps will reproduce the problem?

>>> import argparse
>>> parser = argparse.ArgumentParser(prog='PROG', version='%(prog)s 3.5')
>>> parser.parse_args(['-v'])
%(prog)s 3.5

What is the expected output? What do you see instead?

I expect to see "PROG 3.5", and what I see is "%(prog)s 3.5" (without the 
quotes).

What version of the product are you using? On what operating system?

Using version 1.0.1 on Active Python 2.6.2.2 on Windows Vista.  Problem 
also seems to happen using Jython 2.5.1 on Windows Vista.

Please provide any additional information below.

Original issue reported on code.google.com by [email protected] on 29 Oct 2009 at 9:22

Allow conflicting argument declarations for subparsers

I'd like to have a command line with two subcommands, each of which has the
same option.  This appears to be disallowed in the current version.

Example:

  script cmd1 -v
  script cmd2 -v


Original issue reported on code.google.com by whart222 on 25 Nov 2009 at 8:58

optional subparsers

What steps will reproduce the problem?
parser = argparse.ArgumentParser()
sub = parser.add_subparsers()
sub.add_parser("info")
parser.add_argument("paths", "+")
parser.parse_args(["foo", "bar"])

What is the expected output? What do you see instead?
Expected behavior is that, failing to match one of the subparser inputs
("info"), the parser checks if the argument matches any of the top-level
arguments, in this case the 'paths' multi-arg. In other words, it should be
possible to make the subparser be optional, such that when the subparser
argument fails to retrieve any valid subparser, the remaining args are
parsed as if no subparser exists. At present, it does not seem possible to
make a subparser be optional at all.
Perhaps this could be exposed to the user as:
parser.add_subparsers(nargs=argparse.OPTIONAL)
or something to that effect. Or, allow a default subparser to be specified.
I.e.,

sub = parser.add_subparsers()
info = sub.add_parser("info")
main = sub.add_parser("main")
sub.default = main

I'm sure the point will come up that the current behavior is correct,
because given a subparser like "info", a user could easily make a mistake
like "myapp ino foo bar" and rather than get a safe error be given
something unexpected. For this reason, I think the default behavior is
usually going to be correct. BUT, it would still be nice if it could be
optional, so that developers could be free to make that call. Sometimes the
potential user errors aren't really an issue, and having to explicitly set
a subparse arg every time can be a nuissance.

Original issue reported on code.google.com by [email protected] on 28 Nov 2009 at 3:35

Using default values with the append action

[Originally submitted by [email protected] to python-hosting.org tracker]

The default behavior for options with append action is not very convenient:

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument("--foo", action='append')
>>> parser.parse_args(('--foo=1', '--foo=2'))
Namespace(foo=['1', '2'])
>>> parser.parse_args(())
Namespace(foo=None)

You would expect to get zero or more items in a list for options having an
append action. Now you get either None or one or more items in a list.

Giving a default value to fix this doesn't work:

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument("--foo", action='append', default=[])
>>> parser.parse_args(())
Namespace(foo=[])
>>> parser.parse_args(('--foo=1', '--foo=2'))
Namespace(foo=['1', '2'])
>>> parser.parse_args(())
Namespace(foo=['1', '2'])
>>> parser.parse_args(('--foo=1', '--foo=2'))
Namespace(foo=['1', '2', '1', '2'])

This also applies if you want to have any other default value: if the
default is mutable, the default gets mutated. If the default is immutable,
you get an exception.


Original issue reported on code.google.com by [email protected] on 27 Mar 2009 at 4:59

Installation fails on Linux with the current trunk version (r40)

What steps will reproduce the problem?
1. Download the source 
   $ git svn clone http://argparse.googlecode.com/svn/trunk
(NOTE: autocrlf is false)
   $ cd trunk

2. Run setup.py
   $ python setup.py --help

What is the expected output? 
Help message for the setup.py

What do you see instead?
Traceback (most recent call last):
  File "setup.py", line 40, in <module>
    long_description = read_description(),
  File "setup.py", line 28, in read_description
    main_desc, = re.findall(main_desc_regexp, readme_text, re.DOTALL)
ValueError: need more than 0 values to unpack

What version of the product are you using? On what operating system?
trunk@40 Linux

Please provide any additional information below.

README.txt contains '\r\n' and the corresponding regex -- just '\n'. Python
doesn't converted '\r\n' on Linux.

I've attached the patch that fixes the issue. 


Original issue reported on code.google.com by [email protected] on 11 Sep 2009 at 7:20

Attachments:

optionals with nargs='+' can't be followed by positionals

What steps will reproduce the problem?

>>> import argparse
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('--badger', nargs='+')
>>> parser.add_argument('spam')
>>> parser.parse_args('--badger A B C D'.split())

What is the expected output?

>>> parser.parse_args('--badger A B C D'.split())
Namespace(badger=['A', 'B', 'C'], spam='D')

What do you see instead?

>>> parser.parse_args('--badger A B C D'.split())
usage: PROG [-h] [--badger BADGER [BADGER ...]] spam
PROG: error: too few arguments

Please use labels and text to provide additional information.

Basically, the nargs='+' causes the optional to consume all the arguments
following it, even though we should know that we need to save one for the
final positional argument.

A workaround is to specify '--', e.g.:

>>> parser.parse_args('--badger A B C -- D'.split())
Namespace(badger=['A', 'B', 'C'], spam='D')

Original issue reported on code.google.com by [email protected] on 26 Jul 2009 at 4:28

Feature Request: Positional Argument Aliases

Feature Request:

Suppose I create a positional argument called "build"

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
p_build = subparsers.add_parser("build",help="the build function")

And then I add a bunch of arguments to that subparser. I would also
like a few aliases to this same command. "b" and "compile" should do
the same thing that "build" does. Is there an easy way to tell
argparse that desire without having to define a whole new subparser
for the aliases?

Ideally the add_parser would have an optional argument called aliases
that was a sequence of alternate names for the command. These wouldn't
have to show up in the help, the users would just need to know about
them themselves. 

Original issue reported on code.google.com by tellarite on 18 Aug 2009 at 12:54

Feature Request: Declarative interface using a decorator

Steven,

Thank you very much for argparse. I've used it without problems, liked it
and am very interested to see that it might be included in the stdlib - but
I've also just been looking at Opster and find its declarative interface
(based on a decorator) a breath of fresh air.

What are the chances that argparse could add a declarative interface like this?

I also notice that Opster is 406 source lines versus 1394 for argparse
(using sloccount, so discounting comments), is this because argparse is
still trying to provide optparse compatibility, or because positional args
require the extra code? I haven't actually tried using Opster in anger but
it claims to do subcommands etc. so appears functionally close to argparse,
apart of course from the positional args part.

Would appreciate your thoughts, Steven!

Original issue reported on code.google.com by [email protected] on 15 Sep 2009 at 10:26

Bug in mutually exclusive groups

What steps will reproduce the problem?
1. Use python 2.4  On a linux box when I start python I get 
Python 2.4.3 (#1, Jan 21 2009, 01:10:13)
[GCC 4.1.2 20071124 (Red Hat 4.1.2-42)] on linux2

2. Here is a mimimal sample program

##### Program Start
import sys
import argparse
parser=argparse.ArgumentParser(prog='prog')
group=parser.add_mutually_exclusive_group(required=True)
ll=['-a', '-b', '-c', '-d', '-e', '-f', '-g', '-i', '-j', '-k', '-l', '-m',
'-n', '-o', '-p', '-q', '-r', '-s']
for l in ll[:int(sys.argv[1])]:
    group.add_argument(l)
parser.print_help()
##### Program end

3. Execute "python aa.py 9" (assuming that the above program is in aa.py
and argparse is installed appropriately)

What is the expected output? What do you see instead?
When I execute "python aa.py 8"  I get:
usage: prog [-h] (-a A | -b B | -c C | -d D | -e E | -f F | -g G | -i I)

optional arguments:
  -h, --help  show this help message and exit
  -a A
  -b B
  -c C
  -d D
  -e E
  -f F
  -g G
  -i I

This is exactly as expected.  When I execute "python aa.py 9" I get
Traceback (most recent call last):
  File "ta.py", line 16, in ?
    parser.print_help()
  File "/root/trunk/remus/tools/vmrctl/argparse.py", line 2030, in print_help
    self._print_message(self.format_help(), file)
  File "/root/trunk/remus/tools/vmrctl/argparse.py", line 2013, in format_help
    return formatter.format_help()
  File "/root/trunk/remus/tools/vmrctl/argparse.py", line 262, in format_help
    help = self._root_section.format_help() % dict(prog=self._prog)
  File "/root/trunk/remus/tools/vmrctl/argparse.py", line 192, in format_help
    func(*args)
  File "/root/trunk/remus/tools/vmrctl/argparse.py", line 308, in _format_usage
    positional_usage = format(positionals, groups)
  File "/root/trunk/remus/tools/vmrctl/argparse.py", line 341, in
_format_actions_usage
    start = actions.index(group._group_actions[0])
ValueError: list.index(x): x not in list


This is certainly incorrect.



What version of the product are you using? On what operating system?
This is with version 0.9.1 of argparse, python 2.4.3, on CentOS 5.3

Please provide any additional information below.
The same program run on a mac (os 10.5 with python 2.5 and argparse 0.9.1)
does not have this problem.

I built and installed python 2.6 on centOS 5.3 and had the problem shown above 

Original issue reported on code.google.com by [email protected] on 22 May 2009 at 1:32

values to arguments should be mandatred to be placed immediate

What steps will reproduce the problem?
Consider this example:

        # SET command options
        #
        parser_set = subparsers.add_parser('set', parents=[global_options])
        parser_set.set_defaults(func=setter)

        parser_set.add_argument('set',
                          help="Generate a signature file",
                          action="store", type=str, metavar="apt-offline.sig",
                          default="apt-offline.sig")

        #TODO: Handle nargs here.
        parser_set.add_argument("--install-packages",
dest="set_install_packages", help="Packages that need to be installed",
                          action="store", type=str, nargs='*', metavar="PKG")

        parser_set.add_argument("--install-src-packages",
dest="set_install_src_packages", help="Source Packages that need to be
installed",
                          action="store", type=str, nargs='*',
metavar="SOURCE PKG")

"set" here is a command/argument which expects a value, in this case a file.
Set also has many options. Like the above ones with nargs='*'.

Since argparse is not mandating the placement of the value for the "set"
argument, it fails if that value is places after the option/argument of
type nargs='*'


rrs@champaran:~/devel/apt-offline/apt-offline  (master)$ apt-offline  set
--install-packages foo bar /tmp/foo.uris
usage: apt-offline set [-h] [--verbose] [--test-windows]
                       [--install-packages [PKG [PKG ...]]]
                       [--install-src-packages [SOURCE PKG [SOURCE PKG ...]]]
                       [--src-build-dep] [--release release_name] [--update]
                       [--upgrade] [--upgrade-type upgrade]
                       apt-offline.sig
apt-offline set: error: too few arguments
rrs@champaran:~/devel/apt-offline/apt-offline  (master)$ less
AptOfflineCoreLib.py
rrs@champaran:~/devel/apt-offline/apt-offline  (master)$ sudo apt-offline 
set /tmp/foo.uris --install-packages foo bar
[sudo] password for rrs:

Generating database of package foo, bar,  and its dependencies.

What is the expected output? What do you see instead?
Placements should either be mandated or else argparse should be able to
handle the case I've mentioned above.

What version of the product are you using? On what operating system?
argparse 1.0.1
Linux

Original issue reported on code.google.com by [email protected] on 1 Nov 2009 at 11:13

  • Merged into: #20

Suggestion for a single API function to reduce the amount of typing needed.

Argparse looks promising, but it suffers from the same annoyance that
optparse and others do:  too much typing.  For 90% of the cases when
command line arguments are needed, something like this would work:

http://dpaste.com/31071/

The gist is it's easier to have a simple builder method that just takes a
data array for all arguments, rather than forcing a API user to
repetitively call add_argument on parser for each.  All the existing
methods could stay for the advanced usage, and then this could be an
alternative.

Original issue reported on code.google.com by [email protected] on 10 Apr 2009 at 4:41

customize error messages for invalid type= values

It should be possible to specify the message that type= arguments produce
on error. Right now, your only option is to raise ``ArgumentError(None,
msg)``, which won't include the argument information.

Perhaps _get_value should catch ArgumentErrors thrown and fill in the
argument if it's set to None. Or perhaps we should introduce an
ArgumentTypeError that users could throw specifically for this purpose.

Original issue reported on code.google.com by [email protected] on 25 Sep 2009 at 8:03

'-' should be a valid flag

What steps will reproduce the problem?
parser = argparser.ArgumentParser()
parser.add_argument("-")
parser.parser_args()

What is the expected output? What do you see instead?
Expect a single '-' to be a valid argument just as '+' is considered valid.
Errors out with "must contain characters other than '-'"



This probably seems like it should be uncommon, but a single '-' flag is
something I use regularly in my command line scripts. It's so quick and
easy to type that it makes for a very ideal shortcut, like 'cd -'. I also
have many commands that have add/remove behavior, and in all of these cases
I use +/- flags as shortcut flags to '--add' or '--remove'.
Ideally, an argument parser should place no restrictions on the format of
flags whatsoever. I often can't use the builtin optparse exactly because of
the restrictions it places on flag names.

In the way of suggestions, something that could cover this case and at the
same time many other cases would be to allow flags to be regex objects. I.e.,
parser.add_argument(re.compile("foo"))

Original issue reported on code.google.com by [email protected] on 28 Nov 2009 at 12:27

More robust arguments from files

I changed line 1941 from this: 
arg_strings = args_file.read().splitlines()

to this: arg_strings = args_file.read().strip().split()

Using my approach you have much more flexibility when specifying arguments and 
options in the 
file.



Original issue reported on code.google.com by [email protected] on 15 Sep 2009 at 7:56

parse_known_args() fails when using subcommands

Save the attached script, and run:

 python test.py A --foo

This generates the following output, which indicates that the unknown
'--foo' option is not being ignored:

  usage: test A [-h]
  test A: error: unrecognized arguments: --foo

Original issue reported on code.google.com by whart222 on 26 Nov 2009 at 12:28

Attachments:

convention for reporting program name and version by default

Neither optparse not argparse 1.0.1 provide user friendly reporting of 
program name and version by default.

I propose the following convention to be supported by argument parsing 
library by default.
1. When user calls script.py without arguments the following information is 
displayed
> script.py
Full Program Name, version XXX

Usage: script.py <...>

Short Description

Options:

 ...

> script.py --version
Full Program Name, version XXX
{version template if present with license info or script doc block or ...}

What is the expected output? What do you see instead?
There is `prog` argument to ArgumentParser() that allows to specify script 
name in `"usage: ..."` line, but no argument to specify full program name. 

--version outputs just a number that is not sufficient. In most cases I 
would also like to see revision (as user) or display copyright (as 
developer) or just module docblock that contains both. 

Please provide any additional information below.
It would be nice if argparse could stick to this default output if both 
'version' and 'fullname' information is present and allow to customize 
templates before usage, usage itself, short description and options.

Take a look at 'hg' (or 'svn') command line interface for an example of 
this approach.

Original issue reported on code.google.com by [email protected] on 15 Dec 2009 at 1:21

Unable to configure -v|--version flags when version given to ArgumentParser

What steps will reproduce the problem?
1. `parser = argparse.ArgumentParser(version='foo 0.1')`
2. `parser.add_argument("-v","--verbose", ...)`
3. Get argparse.ArgumentError

argparse allows for a lot of flexibility.  Using argparse for mapping '-V'
to version and '-v' to verbose means you cannot use the version keyword of
argparse.ArgumentParser.  Consider adding flexibility for configuring
argparse generated version flags, instead of hard-coding these.

A lot of command-line programs use '-V' for version and '-v' for verbose,
including `python` itself.

Original issue reported on code.google.com by [email protected] on 17 Aug 2009 at 5:59

improve exception message for nargs=0

Below is the help output for my python script:

C:\IT\work\distro_test>distribute_radix.py -h
usage: distribute_radix.py [-h] [-s SKIP_TAG_GAMES]
                           username password version

This script is designed to eliminate most of the hand work involved in
releasing a new version of the Radix SDK. It will perform all of the
checkouts, builds, installs, and other steps necessary to successfully 
release
a new version of Radix.

positional arguments:
  username              The username that will be used to log into the RGS
                        Subversion and CVS repositories. This is normally 
in
                        the form of "corporate/myname".
  password              Your password. This will be used to log into
                        Subversion and any other services. This password
                        should be the same for most services.
  version               The version number for this release. It must be in 
the
                        form "1.2.3.4".

optional arguments:
  -h, --help            show this help message and exit
  -s SKIP_TAG_GAMES, --skip-tag-games SKIP_TAG_GAMES
                        Specifying this option will prevent games from 
being
                        tagged in CVS. This process takes an exceptionally
                        long time to complete, which is why an option to 
skip
                        it has been provided.

Notice the -s, --skip-tag-games options. It has 'SKIP_TAG-GAMES' after it. 
I want to be able to specify nargs=0 for this, but argparse won't let me. 
It says nargs must be >0. This is simply a "flag", and takes no arguments. 
I also do not want 'SKIP_TAG_GAMES' to show up in the help text.

Please fix this!

Original issue reported on code.google.com by [email protected] on 18 Aug 2009 at 6:56

Show defaults in --help

[Originally reported by [email protected] to the python-hosting.org
tracker]

It would be great if --help would also show the default values for options
(where applicable), or at least if this feature were exposed as an option
in argparse. 

Original issue reported on code.google.com by [email protected] on 28 Mar 2009 at 2:08

Support reading arguments from a file

Feature request:

It would be nice if argparse supported a way to allow users to specify 
additional command line arguments in a file.  E.g.:

  myscript -p foo @argsfile -f bar

where there's a file named "argsfile" in the current working directory 
which contains additional command line arguments.

I've attached a patch that implements this.  It adds an additional keyword 
argument to the ArgumentParser class, named "fromfile_prefix_chars" that 
specifies characters that prefix the name of a file to read additional 
arguments from.  By default this is None, which means never read arguments 
from a file, but if you were to set it to '@', then the above example would 
work.

I've added a test and modified the docs.  I've also verified that the tests 
pass on Linux and Windows, with Python 2.4, 2.5, and 2.6.  Thanks for 
considering this.

Original issue reported on code.google.com by [email protected] on 11 Jul 2009 at 4:58

Attachments:

windows installer needs admin signaling

What steps will reproduce the problem?
1. Run installer on Vista.
2. Get to step prior to copy.

What is the expected output? What do you see instead?
Expected files to copy.  Installer crashes.


What version of the product are you using? On what operating system?
Vista SP1.

Please provide any additional information below.
Installer works when specifically run as administrator.  Most python 
package installers on windows somehow signal the administrator privilege 
requirement so it does not run and crash without privilege elevation.

Original issue reported on code.google.com by [email protected] on 8 Apr 2009 at 12:50

ArgumentError.message triggers DeprecationWarning as of Python 2.6

`BaseException.message` is deprecated as of Python 2.6, its usage triggers
a `DeprecationWarning`.  As `ArgumentError` derives indirectly from
`BaseException`, `ArgumentError.message` triggers this warning too:

{{{
>>> from argparse import ArgumentParser
>>> parser = ArgumentParser()
>>> parser.add_argument('-s', '--spam', type=int)
_StoreAction(option_strings=['-s', '--spam'], dest='spam', nargs=None,
const=None, default=None, type=<type 'int'>, choices=None, help=None,
metavar=None)
>>> parser.parse_args(['-s', 'eggs'])
/usr/lib64/python2.6/site-packages/argparse.py:671: DeprecationWarning:
BaseException.message has been deprecated as of Python 2.6
  self.message = message
/usr/lib64/python2.6/site-packages/argparse.py:678: DeprecationWarning:
BaseException.message has been deprecated as of Python 2.6
  return format % dict(message=self.message,
usage:  [-h] [-s SPAM]
: error: argument -s/--spam: invalid int value: 'eggs'
}}}

A patch against r40, which renames `ArgumentError.message` to
`ArgumentError.error`, is attached.

Original issue reported on code.google.com by lunaryorn on 25 Aug 2009 at 11:42

Attachments:

argparse 1.0.1 has a test failure

What steps will reproduce the problem?
1. Install argparse 1.0.1 (I tried Windows XP and Mac OS X (from SVN)).
2.cd test;  python test_argparse.py

Got this unit test failure:
ERROR: test_argparse_module_encoding (__main__.TestEncoding)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_argparse.py", line 3920, in test_argparse_module_encoding
    text = codecs.open(argparse.__file__, 'r', 'utf8').read()
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/codecs.py", line 666, 
in read
    return self.reader.read(size)
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/codecs.py", line 472, 
in read
    newchars, decodedbytes = self.decode(data, self.errors)
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-1: invalid 
data

Is it because the file being opened (argparse.__file__) is a .pyc file, not a 
text file?

Original issue reported on code.google.com by [email protected] on 15 Sep 2009 at 6:47

optparse incompatibilities are unnecessary

The use of methods like "add_argument" and "ArgumentParser" are 
unnecessarily different than optparse.  I don't see a reason I shouldn't be 
able to replace "from optparse import ..." with "from argparse import ...", 
so long as I don't do anything particularly complicated (like add new 
converters).  These small name changes get in the way of that.  

Also the optparse substitutions (like %prog) should be supported; it would 
only be a couple of lines of extra code to support both those and the 
current argparse %()s substitutions.

Original issue reported on code.google.com by [email protected] on 14 Dec 2009 at 6:20

Adjustments for Python 2.3?

Argparse is great, but I'm wondering if you would be willing to accept
adjustments necessary to make argparse work on Python 2.3. If so, I can
provide the patch (since I'm using it successfully after some minor
changes). Redhat 4, which doesn't reach end-of-life until 2012 has Python
2.3 as its default Python.

What steps will reproduce the problem?
1. Run an argparse program on Python 2.3.

What is the expected output? What do you see instead?
That argparse would work. Instead, list comprehensions and the use of
sorted() cause errors. 

What version of the product are you using? On what operating system?
0.9.1 on Redhat/Scientific Linux 4.6

Please provide any additional information below.
You may contact me at [email protected] (remove animals). 


Original issue reported on code.google.com by [email protected] on 1 May 2009 at 3:51

Provide a way to have default= values parsed from strings

Sometimes it would be nice to be able to supply defaults as strings, and
have the ArgumentParser parse them. For example, if you had a matrix type,
that converted "zero" to, say, ``[[0, 0, 0], [0, 0, 0], [0, 0, 0]]``, then
you might want your default value to still be "zero" for the purposes of
help, so you'd like to write::

  parser.add_argument(..., default="zero", ...)

Right now, defaults are not parsed, so this would fail. It would be nice if
you could supply, say, ``parse_defaults=True`` to the ArgumentParser
constructor to make this work.

Original issue reported on code.google.com by [email protected] on 28 Mar 2009 at 2:12

single file documentation

I wonder if the whole documentation could be compiled in a single file
(HTML or PDF). For printing purposes, handling a single file is easier than
a dozen of html files. 

I have to admit, in this point, the documentation is excellent. Very clear,
with many examples, very well organized... 


Original issue reported on code.google.com by [email protected] on 11 Jun 2009 at 6:39

Allow grouping subparsers together in the help output

Feature request:

The argparse help output groups subparsers in the same list as positional 
arguments:

  usage: test.py [-h] baz {foo,bar} ...

  positional arguments:
    baz
    {foo,bar}

  optional arguments:
    -h, --help  show this help message and exit

This seems to be because subparsers are added to the same argument group as 
positional arguments.  I've attached a patch that adds the subparsers to 
their own argument group if a "subparsers_group_name" keyword argument is 
passed to the ArgumentParser constructor.  This makes subparsers show up in 
their own group:

  usage: test.py [-h] baz {foo,bar} ...

  positional arguments:
    baz

  optional arguments:
    -h, --help  show this help message and exit

  subcommands:
    {foo,bar}

Original issue reported on code.google.com by [email protected] on 13 Jul 2009 at 2:32

Attachments:

improve error message when supplying dest= for positional argument

Using version 1.0.1 I get:

  File "argparse.py", line 1248, in add_argument
TypeError: _get_positional_kwargs() got multiple values for keyword argument 
'dest'

I can see that it might no make sense to specify a dest for a positional 
argument, but the error message isn't very useful ;-)

Original issue reported on code.google.com by [email protected] on 14 Oct 2009 at 11:07

Allow a callable for the 'choices' keyword

[Originally reported by [email protected] to the python-hosting.org tracker]

Right now according to your documentation on here, I see that 'choices'
needs to be a sequence. I could see benefits on maybe changing this to be a
'validator' argument. That way you could create your own callables that
would return True or False if the choice was valid.

For example, say I wanted a float and I knew the min and max that the
choice had to be in between. Offhand I can't think of an easy way to make
this into a sequence that *might* have the float the user chose.

So if the 'validator' is a sequence type, you could still 'if choice in
validator', but just add 'elif callable, if validator(choice)'

Original issue reported on code.google.com by [email protected] on 28 Mar 2009 at 2:24

"from argparse import *" fails

What steps will reproduce the problem?

>>> from argparse import *
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute
'RawTextHelpFormatterArgumentDefaultsHelpFormatter'
>>>

What version of the product are you using?

trunk@62

Please provide any additional information below.

Just a missing comma at argparse.py:87.

Original issue reported on code.google.com by [email protected] on 30 Sep 2009 at 5:35

allow arguments to optionals to have different names

Currently, no matter how many arguments an optional takes, they're all
named the same::

  >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
  >>> parser.add_argument('-c', nargs=2, metavar='X')
  >>> parser.print_help()
  usage: PROG [-c X X]

  optional arguments:
    -c X X

It would be nice to have multiple names sometimes (e.g. "X Y" instead of "X
X" above).

Perhaps this could be achieved by allowing metavar to be a sequence as well
as a string. I'm a little nervous though about the typecheck necessary to
distinguish between strings and other sequences, and the fact that you'd
need to check that the length of the sequence and the nargs value matched.

Original issue reported on code.google.com by [email protected] on 28 Mar 2009 at 2:17

Documentation section 3.1.5 seems to include text for 3.1.4

Section 3.1.5 in the 1.0.1 argparse documentation file describes the 
prefix_chars parameter for the ArgumentParser init call.  However, the last 
two lines of this section appear to be dscussing the proper use of the 
add_help parameter which was discussed in 3.1.4.

What is the expected output? What do you see instead?

see above

What version of the product are you using? On what operating system?

Version 1.0.1 of the argparse documentation

Please provide any additional information below.

Original issue reported on code.google.com by [email protected] on 29 Oct 2009 at 9:33

Support for env/config file hierarchy

Here's a patch to implement configuration hierarchies described in The Art
of Unix Programming [0]

The basic idea is that config information can be pulled out of 

* Global config file
* User local config file
* environment variables
* command line

Higher priority comes later in the list.  This patch allows one to set a
``env_name`` parameter so that actions look in the environment for the
value.  Also provided are ``cfg_section`` and ``cfg_name`` parameters so
that actions can look in .ini style config file files.  The ArgumentParser
constructor has been updated to include a config_files parameter that
accepts a list of instances that support a call ``.get(section, name)``
that will return a value.  Note that it supports a list of files and that
files that come later will override any values previously found.

Example usage:

cfg_str = """[Properties]
author = System User"""
        cfg1 = ConfigParser.ConfigParser()
        cfg1.readfp(StringIO.StringIO(cfg_str))
        cfg_str2 = """[Properties]
author = Matt"""
        cfg2 = ConfigParser.ConfigParser()
        cfg2.readfp(StringIO.StringIO(cfg_str2))
        # cfg1 might be a file found in /etc/conf/...
        # cfg2 might be a local file ~/.config/....
        parser = argparse.ArgumentParser(config_files=[cfg1, cfg2])

        parser.add_argument('--user', cfg_section='Properties',
cfg_name='author', env_name='USER')

Patch is attached

0 - http://www.faqs.org/docs/artu/ch10s02.html

Original issue reported on code.google.com by [email protected] on 28 Sep 2009 at 6:23

Attachments:

parent parser args are positional

What steps will reproduce the problem?
rrs@champaran:~/apt-offline  (master)$ ./apt-offline get /tmp/update.uris --
usage: apt-offline get [-h] [--socket-timeout 30] [-d apt-downloads] [-s .]
                       [--no-check] [-t 1] [--bundle apt-offline-bundle.zip]
                       [--bug-reports]
                       apt-offline.sig
apt-offline get: error: unrecognized arguments: --verbose
rrs@champaran:~/apt-offline  (master)$ ./apt-offline --verbose get
/tmp/update.uris --threads 5 --bundle /tmp/update.zip
rrs@champaran:~/apt-offline  (master)$ ./apt-offline -h
usage: apt-offline [-h] [-v] [--verbose] [--test-windows]
                   {gui,set,install,get} ...

Offline APT Package Manager

positional arguments:
  {gui,set,install,get}

optional arguments:
  -h, --help            show this help message and exit
  -v, --version         show program's version number and exit
  --verbose             Enable verbose messages
  --test-windows        This switch is used while doing testing on windows.

(C) 2005 - 2009 Ritesh Raj Sarraf - This program comes with ABSOLUTELY
NO
WARRANTY. This is free software, and you are welcome to redistribute it
under
the GNU GPL License


What is the expected output? What do you see instead?
I would want to see main parsers args/options to be allowed to be placed
after the sub-parser args/options also.
In the above example, --verbose is a global option. argparse restricts me to
specify the option as the first argument to the main command. It would be
better if it allowed me to specify it anywhere.

What version of the product are you using? On what operating system?
1.0
Linux

Original issue reported on code.google.com by [email protected] on 2 Sep 2009 at 5:30

bug with two letter options and negative number arguments

When a negative number is given as the value of an option (e.g., integer,
float), the number is interpreted as an option and an error is raised. 
The only workaround is to use a long option with '='.

It sure would be nice to have a smarter solution (although I realize that
could be difficult).

What steps will reproduce the problem?
1.
2.
3.

What is the expected output? What do you see instead?


What version of the product are you using? On what operating system?


Please provide any additional information below.

Original issue reported on code.google.com by [email protected] on 9 Oct 2009 at 12:35

API for collecting unrecognized options

It would be nice to be able to specify somehow that unrecognized options
should be collected somewhere instead of raising exceptions. The current
behavior::

  >>> parser = argparse.ArgumentParser(prog='PROG')
  >>> parser.add_argument('--foo')
  >>> parser.parse_args('--foo F --bar --baz'.split())
  usage: PROG [-h] [--foo FOO]
  PROG: error: no such option: --bar

But sometimes you might prefer to have::

  >>> parser = argparse.ArgumentParser(prog='PROG')
  >>> parser.add_argument('--foo')
  >>> parser.parse_known_args('--foo F --bar --baz'.split())
  Namespace(foo='F'), ['--bar', '--baz']

Original issue reported on code.google.com by [email protected] on 28 Mar 2009 at 2:03

--help and --version methods; change defaults

What steps will reproduce the problem?

>>> import argparse
>>> parser = argparse.ArgumentParser(version='0.1')
>>> parser.add_argument('--verbose', '-v', action='store_true')
>>>

(I have used optparse for quite a while and use -v/--verbose all the time)

What is the expected output? What do you see instead?

I expect:
_StoreTrueAction(option_strings=['--verbose', '-v'], dest='verbose',
nargs=0, const=True, default=False, type=None, choices=None, help=None,
metavar=None)

I get:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "argparse.py", line 1287, in add_argument
    return self._add_action(action)
  File "argparse.py", line 1659, in _add_action
    self._optionals._add_action(action)
  File "argparse.py", line 1496, in _add_action
    action = super(_ArgumentGroup, self)._add_action(action)
  File "argparse.py", line 1301, in _add_action
    self._check_conflict(action)
  File "argparse.py", line 1448, in _check_conflict
    conflict_handler(action, confl_optionals)
  File "argparse.py", line 1455, in _handle_conflict_error
    raise ArgumentError(action, message % conflict_string)
argparse.ArgumentError: argument -v/--version: conflicting option string(s): -v

What version of the product are you using? On what operating system?
1.1a1 (os independent)

As of argparse 1.1a1, the --help (unless suppressed) and --version
arguments are created during initialization of the ArgumentParser by calls
to the all-purpose method add_argument (directly in the __init__ method).
This way it is not easily possible to override the default arguments in a
subclass of ArgumentParser; help and version info creation must be
suppressed and done explicitly. This is inconvenient.

"-v" is not commonly used as a --version shorthand:
cp:       --version (-v is --verbose)
find:     --version (no -v or -V argument)
grep: -V, --version
less: -V, --version (no -v argument)
ls:       --version (no -v argument)
sed:  -V, --version
wc:       --version (no -v argument)

InfoZip's zip uses -v for verbose operation *and* version info, but this is
not a serious option...

Some programs even use -h for something else than the help: e.g. for the
(quite important) host argument of database commandline clients, and grep
uses -h/-H for the enforcement/suppression of filenames.

cp:      --help
dirname: --help
find:    --help (no -h or -? argument)
grep:    --help
less:    --help, -? ("Number is required after -h")
ls:      --help (no -h or -? argument)
sed:     --help, -h, -?
unzip:   --help, -h, -?
zip:     --help, -h, -?

As long as the default help and version arguments are created first and
block usage of -h and -v for other options, IMO the default option strings
must be reduced to:

--help (always help, if present)
-?     (dto.)
--version (the only version option which is *always* implemented)

If the creation of these options would be delayed (just before parsing),
-h, -V and *perhaps* -v could be tried as well, but this is another proposal.

For now, I propose to
- change the default option strings (blocking -v is a defect IMO)
- put the calls to add_argument in dedicated methods --
  e.g. add_help_argument, add_version_argument -- which can be easily
  overridden or monkey-patched.

Original issue reported on code.google.com by [email protected] on 6 Nov 2009 at 10:13

Problems with quoted argument strings

What steps will reproduce the problem?
1. Add and option that expects one string argument. (foo --bar baz)
2. For baz, use either an empty string, or a quoted string beginning with
dash: (foo --bar '') (foo --bar '-r is an option string')

What is the expected output? What do you see instead?
I expect it to be parse.  I get a stack trace instead.


What version of the product are you using? On what operating system?
0.9.0 on OSX


Please provide any additional information below.
The test runners don't seem to have a way to simulate quoted strings.

Original issue reported on code.google.com by [email protected] on 15 Apr 2009 at 10:54

Attachments:

mutually exclusive group stops working when specified via parent parser

What steps will reproduce the problem?
What is the expected output? What do you see instead?

I've attached test_mutually_exclusive_parent.py which shows the problem.
ArgumentParser doesn't add its parents' mutually exclusive groups to its
own m.e. group.

What version of the product are you using? On what operating system?
argparse 1.0; Linux

Please provide any additional information below.

As a workaround I add the group in each subparser individually instead of
via the single parent parser ('parents=' keyword argument).

Original issue reported on code.google.com by [email protected] on 11 Sep 2009 at 4:30

Attachments:

Error generating help with add_mutually_exclusive_group

What steps will reproduce the problem?
1. run foo.py -h


What is the expected output? What do you see instead?
Expected is successful help text generation, but an exception is raised.

Here's the dump from python

  args = p.parse_args()
  File "build/bdist.linux-x86_64/egg/argparse.py", line 1514, in parse_args
  File "build/bdist.linux-x86_64/egg/argparse.py", line 1711, in _parse_args
  File "build/bdist.linux-x86_64/egg/argparse.py", line 1651, in
consume_optional
  File "build/bdist.linux-x86_64/egg/argparse.py", line 1580, in take_action
  File "build/bdist.linux-x86_64/egg/argparse.py", line 879, in __call__
  File "build/bdist.linux-x86_64/egg/argparse.py", line 2038, in print_help
  File "build/bdist.linux-x86_64/egg/argparse.py", line 2021, in format_help
  File "build/bdist.linux-x86_64/egg/argparse.py", line 262, in format_help
  File "build/bdist.linux-x86_64/egg/argparse.py", line 192, in format_help
  File "build/bdist.linux-x86_64/egg/argparse.py", line 308, in _format_usage
  File "build/bdist.linux-x86_64/egg/argparse.py", line 341, in
_format_actions_usage
ValueError: list.index(x): x not in list


What version of the product are you using? On what operating system?
argparse 0.9.1  on ubuntu linux 64bit python2.5

Please provide any additional information below.

If you use .add_argument_group instead of .add_mutually_exclusive_group
the help is generated ok.

If you remove any of the add_argument calls, or even remove a single
character from any of the long flags (i.e. '--abc' -> '--ab'), the help is
generated ok.

Original issue reported on code.google.com by [email protected] on 30 Apr 2009 at 2:51

Attachments:

exceptions as arguments

Hi,

I have just discovered argparse, and I have to admit it is quite
impressive. I love it. Good job.

I have a proposal for your consideration. Traditionally I raise my own
exceptions when command line options are not as expected (mandatory options
not provided, or incorrect type or value, etc.) After checking these things
"by hand", I raise my own exceptions, including internal info like the
error code and message users are used to see. 

I was wondering if add_argument() method could include, as optional
arguments, the exceptions to be raised when the several checks fail,
setting as default the ones you are already using. 



Thank you very in advance. 
Regards,
Jose

Original issue reported on code.google.com by [email protected] on 3 Jun 2009 at 3:48

Allow non-mutually exclusive options within a mutually exclusive group

What steps will reproduce the problem?

I've attached a doctest (mutex_with_arg_group.doctest file) that reproduces
the problem.

What is the expected output? What do you see instead?
There should be '|' char in the usage message.

What version of the product are you using? On what operating system?
r61 version, Linux

Please provide any additional information below.
Related problem (that might or might not be a bug) I've described in

http://groups.google.com/group/argparse-users/t/b0910aa82a6f3e52

Original issue reported on code.google.com by [email protected] on 16 Sep 2009 at 10:18

Attachments:

typo in "action" creates hard to diagnose error message

The following contains a typo 

import argparse 
parser = argparse.ArgumentParser(prog="abc") 
parser.add_argument("--version", action="store-true") 
args = parser.parse_args() 

See it? I did "store-true" instead of "store_true". When I run the 
code I get 

Traceback (most recent call last): 
  File "problem.py", line 6, in <module> 
    parser.add_argument("--version", action="store-true") 
  File "/Users/dalke/tmp/argparse.py", line 1264, in add_argument 
    action = action_class(**kwargs) 
TypeError: 'str' object is not callable 

I spent some time trying to figure out what I did wrong, before 
spotting the "-" instead of the "_" in my code. 

Reading the documentation and the code, it appears the goal is to use 
strings for most of the cases but also allow argparse users to 
"specify an arbitrary action by passing an object that implements the 
Action API". 

However, strings are not and cannot implement the Action API. Passing 
in an unrecognized string will always be an error, and likely be a 
typo like mine. 

Could you check for the case of passing in an unsupported string and 
raise an exception with a more useful error message? 

Original issue reported on code.google.com by [email protected] on 18 Oct 2009 at 8:02

argparse-1.0.1 does not install

What steps will reproduce the problem?
1. download
2. unzip
3. run:
# python setup.py install
Traceback (most recent call last):
  File "setup.py", line 40, in <module>
    long_description = read_description(),
  File "setup.py", line 28, in read_description
    main_desc, = re.findall(main_desc_regexp, readme_text, re.DOTALL)
ValueError: need more than 0 values to unpack


Original issue reported on code.google.com by [email protected] on 15 Sep 2009 at 11:51

inconsistent --option=xxx vs --option xxx

I have an option '--si' and and option '--size'  (unintentional)
when used with '=', ambiguous, but when used with ' ', not.

python test_front_end_spec.py --order=3  -e 13.1 --sps='u(2,4)' --alpha
.35 --si 64 --no-notch --size 1000000 


python test_front_end_spec.py --order=3  -e 13.1 --sps='u(2,4)' --alpha
.35 --si=64 --no-notch --size=1000000 
usage: test_front_end_spec.py [-h] [-e ESNODB] [--alpha ALPHA] [--trials
TRIALS] [--order ORDER] [-s SPS] [--size SIZE] [--si SI]
                              [--filter [FILTER]] [--notch [NOTCH]] [--
test_front_end_spec.py: error: ambiguous option: --si=64 could match --si,
--size

Original issue reported on code.google.com by [email protected] on 4 Dec 2009 at 1:19

Bug when parsing long optionals with spaces in the value

What steps will reproduce the problem?
Run this script against the head of svn:

  import argparse
  parser = argparse.ArgumentParser()
  parser.add_argument('--foo')
  print parser.parse_args(['--foo=bar baz'])

What is the expected output? What do you see instead?
Expected output:
Namespace(foo='bar baz')

Actual output:
usage: test.py [-h] [--foo FOO]
test.py: error: unrecognized arguments: --foo=bar baz

What version of the product are you using? On what operating system?
This happens on the head of svn.  Not sure when it was introduced.

Please provide any additional information below.
I've attached a patch that I think fixes it.  Thanks.

Original issue reported on code.google.com by [email protected] on 17 Jul 2009 at 8:28

Attachments:

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.