Giter VIP home page Giter VIP logo

argparse's Introduction

Forums / Blogs / Groups / ...

Build Status

Live demo: https://rcopen.com

Nodeca itself is not expected for wide use. It's intended to replace old RC Design forum software and make programmer's life more comfortable.

But during development we create a lot of useful and popular packages for node.js. See organizations of @puzrin profile. Everything we do is published on github. Enjoy!

argparse's People

Contributors

alchemicalhydra avatar benblank avatar burmisov avatar catwithapple avatar denis-sokolov avatar dpgraham avatar edemaine avatar emazzotta avatar greut avatar ixti avatar lpinca avatar marcin-mazurek avatar maxtaco avatar mourner avatar olegas avatar rlidwka avatar ryanturnerwebdev avatar shkuropat avatar targos 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

argparse's Issues

How can I parse a string that contains quotes that isn't the CLI args?

Seeing as all the example delmit by spaces, how can I tell the program to keep "hello world" all together as one variable?

'use strict';
var ArgumentParser = require('argparse').ArgumentParser;
var parser = new ArgumentParser();
parser.addArgument([ '-f', '--foo' ]);
var args = parser.parseArgs('--foo "hello world"'.split(" "));
console.dir(args);

Outputs:

usage: testing.js [-h] [-f FOO]
testing.js: error: Unrecognized arguments: world".

'choices' argument data key incorrectly parsed

passing an object with 'choices' equal to ['a', 'b', 'c'] to addArgument will cause the generated usage information to incorrectly say that {0,1,2} are the acceptable values.

Looks like some calls to _.isObject() are in place that should be to .isArray(). (.isObject() returns true for objects AND arrays.) Coming up with a patch.

Inconsistent naming

{
     constant: [str | int | ...],
     type    : [str | int | ...],
     action  : [storeConst | appendConst | ...]
}

It should be

{
     constant: [String | Number | ...],
     type    : [String | Number | ...],
     action  : [storeConst | appendConst | ...]
}

or

{
     constant: [int | str | ...],
     type    : [str | int | ...],
     action  : [store_const | append_const | ...]
}

And so on...

Personally, I prefer the last one

storeTrue and store for one argument?

I'm looking to add a flag where if no values are given such as --flag it just stores true and if values are given --flag value then they are stored as normal.

Is there a way to do this with argparse?

conflictHandler 'resolve' error

For the new 'resolve' case in base.js, parser.formatHelp() produces

usage: _mocha [-h] [--foo FOO] [--foo FOO]
Optional arguments:
  --foo FOO  new foo

That is, [-foo FOO] appears twice in usage, and the usual -h, --help Show ... line is missing.

The help message should be

usage: _mocha [-h] [--foo FOO]
Optional arguments:
  -h, --help  Show this help message and exit.
  --foo FOO  new foo

incomplete error testing for nargs

Several python issues deal with nargs related error messages:

http://bugs.python.org/issue16970 argparse: bad nargs value raises misleading message

http://bugs.python.org/issue9849 Argparse needs better error handling for nargs

nargs can be one of several strings, e.g. '*', '...' (Const.PARSER) or an integer. But checking for valid values is ad hoc.

One issue is when or where nargs can be 0 or <0

parser.addArgument('foo',{nargs:0})

triggers an error by _StoreAction, saying that nargs should be >0. However

parser.addArgument('foo',{nargs:-1})

is accepted. parser.parseArgs([]) returns { foo: [] }, but formatUsage has problems formatting a metavar (in Javascript, not in the Python).

Another issue is what happens if nargs isn't one of the recognized strings or an integer (e.g. nargs:'1' or nargs:'test'). Neither Python or Javascript raises an error in addArgument. Instead the problems arise in either parseArgs or formatHelp. In both the ultimate issue is whether it can replicate a string nargs times.

In the most recent Python release, addArgument does test whether a tuple metavar matches nargs, and in the process discovers invalid nargs values. But even with this the error messages are not clear. Also parser.addArgument gets this test, but group.addArgument does not.

REMAINDER nargs not working

I was trying to use the REMAINDER nargs feature, as follows:

var argparse = require('argparse');

var parser = new argparse.ArgumentParser();

parser.addArgument(['remaining'], { nargs: argparse.Const.REMAINDER });

console.log(parser.parseArgs(['--foo']));

But when I run the above script, I get:

$ node foo.js
usage: foo.js [-h] ...
foo.js: error: Unrecognized arguments: --foo.

Is the REMAINDER feature supported? If so, am I invoking it correctly? Thanks!

"Type" parameter not functioning as expected

I have parameter data like this (nevermind the custom format):

  [['-p', '--port'] , {
    defaultValue: 4723
    , required: false
    , type: 'int'
    , example: "4723"
    , help: 'Port to listen on'
    , nargs: 1
  }],

And when I do typeof args.port later on, the type comes back as object, no matter whether I use 'int' or 'integer' or 'string'.

How is this option intended to be used? I want to make sure args.port is an integer. Interestingly, using 'int' or 'string' or function(x) { return parseInt(x, 10); } all work, i.e., they don't crash argparse, but they don't make args.port an integer or anything else. Using 'number', however, crashes argparse. So something is happening, but just not what I expect.

Undefined context

parser.addArgument(['-t', '--type'], {
    defaultValue: 'regular',

    type (value) {
        console.log(this) // undefined
    },

    help: 'Account type can be [regular | pdd | external]'
});

Why this is undefined?

npmignore

Hi, I'm trying to reduce the dependency size in my module and was wondering if you could .npmignore everything expect for:

lib
index.js

Help Lines Wrap Incorrectly

The help lines I have that are long enough to wrap only ever put the last word on the next line. If you replace the if statement at line 774 of lib/help/formatter.js with the following it should fix it.

if (wrapEnd !== line.length && delimiters.indexOf(line[wrapEnd - 1]) < 0) {
  wrapEnd = wrapStart + (re.exec(line.substring(wrapStart, wrapEnd)) || {}).index + 1;
}

This should put the wrap point at the last delimiter in the desired segment instead of the last delimiter in the entire string. Also I think I improved the condition to determine if the last character in the substring is a delimiter.

Command line completition

It would be great to have command line completition given by the framework.
Right now I haven't found any library which could be opt-in to argparse to support command completition.

Subparser alias is not shown in --help output

JS example script:

#!/usr/bin/env node

var ArgumentParser = require('argparse').ArgumentParser;

var parser, subparsers, args;
var testArg1, testArg2;

// Main parser setup.
parser = new ArgumentParser({
  'version': '1.0.0',
  'addHelp': true,
  'description': 'Description.',
  'epilog': 'Epilog.'
});
subparsers = parser.addSubparsers({
  dest: 'posarg'
});

// Test arguments.
testArg1 = subparsers.addParser('c1', {addHelp: true, help: 'c1 help'});
testArg1.addArgument(['-f', '--foo'], {
  action: 'store',
  help: 'foo'
});
testArg2 = subparsers.addParser('c2', {
  aliases: ['co'],
  addHelp: true,
  help: 'c2 help'
});
testArg2.addArgument(['-b', '--bar'], {
  action: 'store',
  type: 'int',
  help: 'bar'
});

args = parser.parseArgs();

Python example script (running in 3.4):

#!/usr/bin/env python
import argparse

argparser = argparse.ArgumentParser(add_help=True)
argparser.description = 'Description.'
argparser.epilog = 'Epilog.'
argparser.add_argument('--version', action='version', version='1.0.0')
subparsers = argparser.add_subparsers(
  dest='posarg'
)

test_arg_1 = subparsers.add_parser('c1', help='c1 help')
test_arg_1.add_argument('-f', '--foo', action='store', help='foo')

test_arg_2 = subparsers.add_parser('c2', aliases=['co'], help='c2 help')
test_arg_2.add_argument('-b', '--bar', action='store', type=int, help='bar')

args = argparser.parse_args()

When running these scripts, there's one main discrepancy: the JS version shows the second subparser as c2 c2 help and the Python version shows c2 (co) c2 help. It would be good to show the alias in the JS version as well.

Single character options can be concatenated with their arguments

I found this behavior in the source code argument_parser.js:816. It is explicitly made to act this way. But it's not what the Python version is doing. I don't think single character options could be concatenated with their arguments. Consider the following example:

parser.addArgument(['-start-date'], ...);
parser.addArgument(['-sum'], ...);

Now I got an ambiguity and it just won't work. Could you guys make it work like the Python one? Thanks!

argparse does not accept negative values

argparse .js does not accept negative values, either as positional arguments or arguments for options

The problem, apparently, is that Python not [] and not [True] is different from JS ![] and ![true]. The original Python is:

class _ActionsContainer(object):

    def __init__(...
        # whether or not there are any optionals that look like negative
        # numbers -- uses a list so it can be shared and edited
        self._has_negative_number_optionals = []
        ...
    def _add_action(self, action):
        ...
        # set the flag if any option strings look like negative numbers
        for option_string in action.option_strings:
            if self._negative_number_matcher.match(option_string):
                if not self._has_negative_number_optionals:
                    self._has_negative_number_optionals.append(True)

So self._has_negative_number_optionals is either [] or [True], and not [] == True, not[True]==False

later during parsing it is used:

class ArgumentParser(_AttributeHolder, _ActionsContainer):
...
    def _parse_optional(self, arg_string):
    ...
        if self._negative_number_matcher.match(arg_string):
            if not self._has_negative_number_optionals:
                return None

in javascript ![true] and ![] both are false

!_.any(self._has_negative_number_optionals) will behave as in Python.

one possible correction then is to test it as in

    if (optionString.match(self._regexpNegativeNumber)) {
      if (!_.any(self._hasNegativeNumberOptionals)) {
        self._hasNegativeNumberOptionals.push(true);
      }
    }

also in ArgumentParser.prototype._parseOptional = function (argString)

It is tempting to try to simplify things by replacing the [],[true] with false, true. But as shown in the initialization of ArgumentGroup objects, this attribute is shared among 3 groups, the parser itself, and its _optionals and _positionals. Modifying the list value preserves this sharing, while assigning a new value would break it.

ArgumentError class

The Python code creates an ArgumentError class. This JS implementation uses an argumentErrorHelper(), which formats the same message, but returns a (plain) Error object. Below is an ArgumentError subclass that is a little closer in style to the Python. It could also be used in a err instanceof ArgumentError test if needed.

function ArgumentError(argument, message) {
  this.argument = argument || null;
  this.message = message || "";
  this.name = "ArgumentError";
  Error.captureStackTrace(this, this);
  this.argumentName = this.argument.getName();
  }
}
util.inherits(ArgumentError, Error);
ArgumentError.prototype.toString = function () {
  var astr;
  if (this.argumentName) {
    astr = "argument \"" + this.argumentName + "\": " + this.message;
  } else {
    astr = "" + this.message;
  }
  return this.name + ": " + astr;
};

action: 'append' on positionals

The 'append' action doesn't seem to work with positional arguments. With the following setup:

#!/usr/bin/env node
var argparse = require('argparse');

var parser = new argparse.ArgumentParser();
parser.addArgument(['foo'], {
    action: 'append',
});

console.log(parser.parseArgs().foo);

a single argument works fine:

$ ./test.js one
['one']

but multiple doesn't:

$ ./test.js one two
usage: test.js foo
test.js: error: Unrecognized arguments: two.

The expected output in the latter case is of course ['one', 'two'].

I experimented with various type values (most notably 'string' and function(arg) { return arg.split(/\s/); }) but to no avail.

FileType

The Python FileType accepts a filename string, and returns an opened file, or returns an ArgumentTypeError with the IOError message. It can also return stdin or stdout if the string is '-'.

I think a nodejs equivalent would be a ReadStream or WriteStream, or process.stdin, stdout, which are also streams. Opening the file first (with fs.openSync), before creating the stream, lets argparse return an error message if there is a problem.

I propose submitting this type as an example file, with a unix cat like functionality. This type is probably not as useful in nodejs as in Python, since node is meant more for asynchronous server like applications than for scripting.

Double enclosed appendable params

I've noticed, that new argparse releases completely fuckuped our ndoc.

Input data (process.argv):

[ 'node',
  '/home/vitaly/.nvm/v0.8.17/bin/ndoc',
  'lib/',
  'examples/' ]

argparse config:

cli.addArgument(['paths'], {
  help:         'Source files location',
  metavar:      'PATH',
  action:       'append',
  nargs:        '+'
});

result:

{ paths: [ [ 'lib/', 'examples/' ] ], use: [] }

Note, that paths become double stacked array. It should be just simple array of strings. It was ok in 1.0.3

Namespace to object?

Is there any reason that when I console.log(parser.parseArgs()) I get Namespace { config: 'script/config1.js' };

It wouldn't normally be a problem as when I do Object.keys(parser.parseArgs()) I get [ 'config' ] which I would expect.

But when using extend and js-extend I was getting a funky "isset": [Function], "set": [Function], "get" [Function], "unset": [Function] added to the output object.

I originally throught it was extend and js-extend doing it, but once I taken parseArgs out of the equation, it cleared up.

I am not looping through Object.keys in my own extend function to bypass this, but don't know what funkiness that your module is doing to add this strange "Namespace" to the output object.

  • Colin.

subcommand aliases not resolved

Given this script (test.js):

ArgumentParser = require('argparse').ArgumentParser;

var parser = new ArgumentParser({
  addHelp: true
});

var subparser = parser.addSubparsers({
  title: 'Actions',
  dest: 'action'
});

var list = subparser.addParser('list', {
  description: 'Lists all templates that you have added.',
  aliases: ['ls', 'all'],
  addHelp: false
});

console.log(parser.parseArgs());

Calling it with node test.js ls prints { action: 'ls' }, rather than { action: 'list' }. I think this is a bug... or at least a pain because I need to use list.setDefaults({action: 'list'}); to make it only print out a single name regardless of the alias.

'-ku' and '-uk' give different results than '-k -u'

http://bugs.python.org/issue16142
ArgumentParser inconsistent with parse_known_args

Users want:

parser.add_argument('-k','--known',action='store_true')
print(parser.parse_known_args(['-k','-u']))
print(parser.parse_known_args(['-ku']))
print(parser.parse_known_args(['-uk']))

to all produce the same output:

(Namespace(known=True), ['-u'])

Currently '-ku' gives an error, and '-uk' goes into the extras.

I submitted a patch to fix the '-ku' case (without breaking any tests).

Support For Optional Subparsers

It would be helpful to be able to make subcommands optional. Instead we get "error: too few arguments"

I believe this is supported in the latest python version.

`addArgument([...],{defaultValue:0})` does not work

Trying to set the Action defaultValue to a falsie via addArgument does not work.
The problem is with the if (!options.defaultValue) { test. It is supposed to detect
when this option is not defined, but instead it rejects all falsies, including 0.
A better translation of the Python block is:

  // closer Python translation
  if (_.isUndefined(options.defaultValue)) {
    var dest = options.dest;
    if (_.has(this._defaults, dest)) {
      options.defaultValue = this._defaults[dest];
    } else if (!_.isUndefined(this.argumentDefault)) {
      options.defaultValue = this.argumentDefault;
    }
  }

(options.defaultValue == null) would also work, due to how == is defined.

On a related note, the getDefault function does not work, returning null all the time
It is not called by other argparse code, but can be called by the user. Part of the problem is the test on action.defaultValue. But also the return action.defaultValue only returns from the inner function, not outer one.

// corrected version, based on a Coffeescript implementation
ActionContainer.prototype.getDefault = function (dest) {
  var result, _ref;
  // Python: self._defaults.get(dest, None)
  // coffee: result = this._defaults[dest] ? null
  result = (_ref = this._defaults[dest]) != null ? _ref : null;
  this._actions.forEach(function (action) {
    if (action.dest === dest && action.defaultValue !== null) {
      result = action.defaultValue;
    }
  });
  return result;
};

In looking for other uses of defaultValue, I found an error in ActionContainer._registryGet. It incorrectly translates the Python default=None optional argument. The defaultValue argument in this case is not connected with the previously one. The simplest correction is to simply omit the test, since the function is always called with 3 arguments.

ActionContainer.prototype._registryGet = function (registryName, value, defaultValue) {
  // defaultValue = defaultValue || null; // does not implement "default=None"
  return this._registries[registryName][value] || defaultValue;
};

argparse handling multiple "--" in args improperly

Python Issue 13922

ArgumentParser._getValues() deletes all '--' from the argStrings if the action is not PARSER or REMAINDER.

A patch in the Python development branch changes that to delete only the 1st '--'. However this ends up deleting only the first in each cluster of positional strings. I have submitted a patch that deletes only one '--', the one that puts a '-' in the argStringsPattern near the start of ArgumentParser._parseKnownArgs.
http://bugs.python.org/issue13922#msg186884

This change might apply if argparse is used to pass a list of arguments to another program that uses '--' in the same way.

Incorrect default for prog

It looks like the docs for the prog parameter were copied from the Python docs:

The name of the program (default: sys.argv[0])

I think you mean:

The name of the program (default: process.argv[0])

needs message for "expected argument to --foo"

Say that an option foo expects an argument of type string but doesn't get one.

./my-parser.js --foo

The error is

my-parser.js build: error: undefined

I would expect instead

my-parser.js build: error: "option --foo requires an argument"

Exception displaying help when script name is quite long

Having a long script name like extract-display-actions-from-action-provider-log-file I get the following exception when using help option:

extract-display-actions-from-action-provider-log-file.coffee -h
TypeError: parts.forEach is not a function
  at _getLines (D:\dev\svn\working-copies\ips\ips-cki-web-ui\tools\node_modules\argparse\lib\help\formatter.js:378:15)
  at HelpFormatter._formatUsage (D:\dev\svn\working-copies\ips\ips-cki-web-ui\tools\node_modules\argparse\lib\help\formatter.js:416:17)
  at D:\dev\svn\working-copies\ips\ips-cki-web-ui\tools\node_modules\argparse\lib\help\formatter.js:66:17
  at Array.map (native)
  at Section.formatHelp (D:\dev\svn\working-copies\ips\ips-cki-web-ui\tools\node_modules\argparse\lib\help\formatter.js:60:26)
  at HelpFormatter.formatHelp (D:\dev\svn\working-copies\ips\ips-cki-web-ui\tools\node_modules\argparse\lib\help\formatter.js:299:32)
  at ArgumentParser.formatUsage (D:\dev\svn\working-copies\ips\ips-cki-web-ui\tools\node_modules\argparse\lib\argument_parser.js:1035:20)
  at ArgumentParser.printUsage (D:\dev\svn\working-copies\ips\ips-cki-web-ui\tools\node_modules\argparse\lib\argument_parser.js:1091:27)
  at ArgumentParser.error (D:\dev\svn\working-copies\ips\ips-cki-web-ui\tools\node_modules\argparse\lib\argument_parser.js:1167:8)
  at ArgumentParser.parseKnownArgs (D:\dev\svn\working-copies\ips\ips-cki-web-ui\tools\node_modules\argparse\lib\argument_parser.js:297:10)
  at ArgumentParser.parseArgs (D:\dev\svn\working-copies\ips\ips-cki-web-ui\tools\node_modules\argparse\lib\argument_parser.js:234:21)
  at Object.res.process (D:\dev\svn\working-copies\ips\ips-cki-web-ui\tools\impl\extract-display-actions-from-action-provider-log-file\cli.j
s:73:24)
  at Object.<anonymous> (D:\dev\svn\working-copies\ips\ips-cki-web-ui\tools\extract-display-actions-from-action-provider-log-file.coffee:24:
12)
  at Object.<anonymous> (D:\dev\svn\working-copies\ips\ips-cki-web-ui\tools\extract-display-actions-from-action-provider-log-file.coffee:2:1
)
  at Module._compile (module.js:398:26)
  at Object.exports.run (d:\dev\lng\JavaScript\node-globals\node_modules\coffee-script\lib\coffee-script\coffee-script.js:134:23)
  at compileScript (d:\dev\lng\JavaScript\node-globals\node_modules\coffee-script\lib\coffee-script\command.js:224:29)
  at compilePath (d:\dev\lng\JavaScript\node-globals\node_modules\coffee-script\lib\coffee-script\command.js:174:14)
  at Object.exports.run (d:\dev\lng\JavaScript\node-globals\node_modules\coffee-script\lib\coffee-script\command.js:98:20)
  at Object.<anonymous> (d:\dev\lng\JavaScript\node-globals\node_modules\coffee-script\bin\coffee:7:41)
  at Module._compile (module.js:398:26)
  at Object.Module._extensions..js (module.js:405:10)
  at Module.load (module.js:344:32)
  at Function.Module._load (module.js:301:12)
  at Function.Module.runMain (module.js:430:10)
  at startup (node.js:141:18)
  at node.js:980:3

Inconsistent naming

{
     constant: [str | int | ...]
     action: [storeConst | appendConst | ...]
}

It should be

{
     const: [String | Number | ...]
     action: [storeConst | appendConst | ...]
}

or

{
     const: [int | str | ...]
     action: [store_const | append_const | ...]
}

I see some contradictions like:

  1. const is not reserved word as an object property
  2. There'a no int and str types in JavaScript
  3. Why camelCase (so why --test-key not transformed to testKey) ?

And so on...

Personally, I prefer the last one

Change in Python3.4 on when the type function is called on the defaultValue

Python development issues 12776 and 15906
http://bugs.python.org/issue12776
"When specifying a function to be called in type keyword argument of add_argument(), the function is actually called twice (when a default value is set and then when the argument is given)."

In the current dev Python version, this patch moves a self._get_value(action, default) from the start of parse_known_args to near the end of _parse_known_args, after it is known whether the default value is needed or not. This prevents unnecessary evaluation of the argument default value. For types like float this does not matter, but for FileType we don't want to open the default file if it is not needed.

I just raised the issue of what happens with a positional argument with nargs='_':
add_argument('foo', type=FileType('r'), default='anyfile', nargs='_')

This is the biggest change in the Python argparse development pipeline. We should keep an eye on what develops.

argparse doesn't allow optionals within positionals

Python issue http://bugs.python.org/issue14191

Some unix coders are used to freely intermixing optionals and positionals. optparse, which argparse is supposed to replace, parses all of the optionals, and puts everything else in an extras array. This is like parseKnownArgs but with freer intermixing.

A proposed solution is to write a parser.parseIntermixedArgs that does a 2 step parse, first parse the input with only the conditionals arguments, and then parse the extras with the positionals.

Add defaults to the description with -h?

So when you do -h it can show what the current defaults are?

Optional arguments:
  -h, --help     Show this help message and exit.
  -v, --version  Show program's version number and exit.
  --port PORT    Port Number (8080)
  --type TYPE    Location of Type File (scripts/type.js)

Doesn't have to be in brackets, it's just how I have currently added it.
For now I have added them directly into the "help" of the addArgument, but I thought if it could display the defaults by itself it would be nice. That way I don't have to change the default value in 2 locations.

'parents' is broken

Sample code:

ArgumentParser      = require('argparse').ArgumentParser

parentParser = new ArgumentParser()
parentParser.addArgument([ '--x' ])

parser = new ArgumentParser({
    parents: [parentParser]
})

Produces:

$ node test.js

/test/node_modules/argparse/lib/argument_parser.js:124
    this._addContainerActions(parent);
         ^
TypeError: Cannot call method '_addContainerActions' of undefined
    at /test/node_modules/argparse/lib/argument_parser.js:124:10
    at Array.forEach (native)
    at new ArgumentParser (/test/node_modules/argparse/lib/argument_parser.js:123:19)
    at Object.<anonymous> (/test/bin/test.js:6:10)
    at Module._compile (module.js:446:26)
    at Object..js (module.js:464:10)
    at Module.load (module.js:353:31)
    at Function._load (module.js:311:12)
    at Array.0 (module.js:484:10)
    at EventEmitter._tickCallback (node.js:190:38)

Help string default placeholder

In Python I can set the default, and set the help text to "Some help... default: %(default)s" and it fills in the default for me. I tried exactly that in node and get error: [_.sprintf] property "default" does not exist. I am setting a default.

Failure to recognize negative scientific notation (with nargs:2)

On stackoverflow I came across an argparse.py issue that also affects this version. It has to do with recognizing negative numbers like -2e4. The negativeNumberMatcher does not handle scientific notation.

However the issue only rises in special circumstances such as a nargs:2 case, and there are work arounds.

ArgumentParser = require('argparse').ArgumentParser

parser = new ArgumentParser({debug:true});
parser.addArgument(['--xlim'], {nargs: 2, type: 'float'});

args = parser.parseArgs(['--xlim', '-.002', '1e4']);
console.log(args);
// { xlim: [ -0.002, 10000 ] }

args = parser.parseArgs(['--xlim', '-2e3', '1e4'])
// TypeError: argument "--xlim": Expected 2 argument(s)

http://stackoverflow.com/questions/9025204/python-argparse-issue-with-optional-arguments-which-are-negative-numbers
http://bugs.python.org/issue9334
may be a related issue (parsing ['-a','-one','-two'] where (['-a',{nargs:2}). That is, should '-one' be interpreted as an optional, or as an argument to '-a'?

argparse: optional subparsers

Python Issue 9253

This issue requested the ability to make the subparsers argument optional. In the latest development release that has become the default. Previous versions had a test near the end of _parseKnownArgs:

// if we didn't use all the Positional objects, there were too few
// arg strings supplied.
if (positionals.length > 0) {
  self.error('too few arguments');
}

which had the effect of warning if a subparsers argument was missing, even though the corresponding action.required attribute was false. This was test was dropped in the latest development version, leaving it up to the following test to flag missing arguments:

// make sure all required actions were present
self._actions.forEach(function (action) {
  if (action.required) {
    if (_.indexOf(seenActions, action) < 0) {
      self.error(format('Argument "%s" is required', action.getName()));
    }
  }
});

I have submitted a Python patch
http://bugs.python.org/issue9253#msg186695
that makes ActionSubparsers.required = true by default. I also added custom a getName() method to this subclass to give a meaningful name (in case dest or metvar are not set). The Python code also had problems formatting the error message when getName return a None, but I don't think that's an issue in the javascript code.

ArgumentTypeError

Python creates an ArgumentTypeError class, which a user-defined-type function can use. It does not add any functionality, but parser._getValue() uses the error class to distinguish between errors that get a standardized message: invalid ... value (ValueError, TypeError), and ones whose is message is passed on (ArgumentTypeError). In effect ArgumentTypeError gives the user more control of the error message. For example in a FileType, IOErrors should be passed on to the user.

In issue #45, named types get the standardized message, while anonymous ones get a customized one. This could be changed to distinguish between TypeErrors and ArgumentTypeErrors.

function ArgumentTypeError(msg) {
  Error.captureStackTrace(this, this);
  this.message = msg || 'Argument Error';
  this.name = 'ArgumentTypeError';
}
util.inherits(ArgumentTypeError, Error);

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.