No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

257 líneas
8.2 KiB

hace 3 años
  1. argparse
  2. ========
  3. [![Build Status](https://secure.travis-ci.org/nodeca/argparse.svg?branch=master)](http://travis-ci.org/nodeca/argparse)
  4. [![NPM version](https://img.shields.io/npm/v/argparse.svg)](https://www.npmjs.org/package/argparse)
  5. CLI arguments parser for node.js. Javascript port of python's
  6. [argparse](http://docs.python.org/dev/library/argparse.html) module
  7. (original version 3.2). That's a full port, except some very rare options,
  8. recorded in issue tracker.
  9. **NB. Difference with original.**
  10. - Method names changed to camelCase. See [generated docs](http://nodeca.github.com/argparse/).
  11. - Use `defaultValue` instead of `default`.
  12. - Use `argparse.Const.REMAINDER` instead of `argparse.REMAINDER`, and
  13. similarly for constant values `OPTIONAL`, `ZERO_OR_MORE`, and `ONE_OR_MORE`
  14. (aliases for `nargs` values `'?'`, `'*'`, `'+'`, respectively), and
  15. `SUPPRESS`.
  16. Example
  17. =======
  18. test.js file:
  19. ```javascript
  20. #!/usr/bin/env node
  21. 'use strict';
  22. var ArgumentParser = require('../lib/argparse').ArgumentParser;
  23. var parser = new ArgumentParser({
  24. version: '0.0.1',
  25. addHelp:true,
  26. description: 'Argparse example'
  27. });
  28. parser.addArgument(
  29. [ '-f', '--foo' ],
  30. {
  31. help: 'foo bar'
  32. }
  33. );
  34. parser.addArgument(
  35. [ '-b', '--bar' ],
  36. {
  37. help: 'bar foo'
  38. }
  39. );
  40. parser.addArgument(
  41. '--baz',
  42. {
  43. help: 'baz bar'
  44. }
  45. );
  46. var args = parser.parseArgs();
  47. console.dir(args);
  48. ```
  49. Display help:
  50. ```
  51. $ ./test.js -h
  52. usage: example.js [-h] [-v] [-f FOO] [-b BAR] [--baz BAZ]
  53. Argparse example
  54. Optional arguments:
  55. -h, --help Show this help message and exit.
  56. -v, --version Show program's version number and exit.
  57. -f FOO, --foo FOO foo bar
  58. -b BAR, --bar BAR bar foo
  59. --baz BAZ baz bar
  60. ```
  61. Parse arguments:
  62. ```
  63. $ ./test.js -f=3 --bar=4 --baz 5
  64. { foo: '3', bar: '4', baz: '5' }
  65. ```
  66. More [examples](https://github.com/nodeca/argparse/tree/master/examples).
  67. ArgumentParser objects
  68. ======================
  69. ```
  70. new ArgumentParser({parameters hash});
  71. ```
  72. Creates a new ArgumentParser object.
  73. **Supported params:**
  74. - ```description``` - Text to display before the argument help.
  75. - ```epilog``` - Text to display after the argument help.
  76. - ```addHelp``` - Add a -h/–help option to the parser. (default: true)
  77. - ```argumentDefault``` - Set the global default value for arguments. (default: null)
  78. - ```parents``` - A list of ArgumentParser objects whose arguments should also be included.
  79. - ```prefixChars``` - The set of characters that prefix optional arguments. (default: ‘-‘)
  80. - ```formatterClass``` - A class for customizing the help output.
  81. - ```prog``` - The name of the program (default: `path.basename(process.argv[1])`)
  82. - ```usage``` - The string describing the program usage (default: generated)
  83. - ```conflictHandler``` - Usually unnecessary, defines strategy for resolving conflicting optionals.
  84. **Not supported yet**
  85. - ```fromfilePrefixChars``` - The set of characters that prefix files from which additional arguments should be read.
  86. Details in [original ArgumentParser guide](http://docs.python.org/dev/library/argparse.html#argumentparser-objects)
  87. addArgument() method
  88. ====================
  89. ```
  90. ArgumentParser.addArgument(name or flag or [name] or [flags...], {options})
  91. ```
  92. Defines how a single command-line argument should be parsed.
  93. - ```name or flag or [name] or [flags...]``` - Either a positional name
  94. (e.g., `'foo'`), a single option (e.g., `'-f'` or `'--foo'`), an array
  95. of a single positional name (e.g., `['foo']`), or an array of options
  96. (e.g., `['-f', '--foo']`).
  97. Options:
  98. - ```action``` - The basic type of action to be taken when this argument is encountered at the command line.
  99. - ```nargs```- The number of command-line arguments that should be consumed.
  100. - ```constant``` - A constant value required by some action and nargs selections.
  101. - ```defaultValue``` - The value produced if the argument is absent from the command line.
  102. - ```type``` - The type to which the command-line argument should be converted.
  103. - ```choices``` - A container of the allowable values for the argument.
  104. - ```required``` - Whether or not the command-line option may be omitted (optionals only).
  105. - ```help``` - A brief description of what the argument does.
  106. - ```metavar``` - A name for the argument in usage messages.
  107. - ```dest``` - The name of the attribute to be added to the object returned by parseArgs().
  108. Details in [original add_argument guide](http://docs.python.org/dev/library/argparse.html#the-add-argument-method)
  109. Action (some details)
  110. ================
  111. ArgumentParser objects associate command-line arguments with actions.
  112. These actions can do just about anything with the command-line arguments associated
  113. with them, though most actions simply add an attribute to the object returned by
  114. parseArgs(). The action keyword argument specifies how the command-line arguments
  115. should be handled. The supported actions are:
  116. - ```store``` - Just stores the argument’s value. This is the default action.
  117. - ```storeConst``` - Stores value, specified by the const keyword argument.
  118. (Note that the const keyword argument defaults to the rather unhelpful None.)
  119. The 'storeConst' action is most commonly used with optional arguments, that
  120. specify some sort of flag.
  121. - ```storeTrue``` and ```storeFalse``` - Stores values True and False
  122. respectively. These are special cases of 'storeConst'.
  123. - ```append``` - Stores a list, and appends each argument value to the list.
  124. This is useful to allow an option to be specified multiple times.
  125. - ```appendConst``` - Stores a list, and appends value, specified by the
  126. const keyword argument to the list. (Note, that the const keyword argument defaults
  127. is None.) The 'appendConst' action is typically used when multiple arguments need
  128. to store constants to the same list.
  129. - ```count``` - Counts the number of times a keyword argument occurs. For example,
  130. used for increasing verbosity levels.
  131. - ```help``` - Prints a complete help message for all the options in the current
  132. parser and then exits. By default a help action is automatically added to the parser.
  133. See ArgumentParser for details of how the output is created.
  134. - ```version``` - Prints version information and exit. Expects a `version=`
  135. keyword argument in the addArgument() call.
  136. Details in [original action guide](http://docs.python.org/dev/library/argparse.html#action)
  137. Sub-commands
  138. ============
  139. ArgumentParser.addSubparsers()
  140. Many programs split their functionality into a number of sub-commands, for
  141. example, the svn program can invoke sub-commands like `svn checkout`, `svn update`,
  142. and `svn commit`. Splitting up functionality this way can be a particularly good
  143. idea when a program performs several different functions which require different
  144. kinds of command-line arguments. `ArgumentParser` supports creation of such
  145. sub-commands with `addSubparsers()` method. The `addSubparsers()` method is
  146. normally called with no arguments and returns an special action object.
  147. This object has a single method `addParser()`, which takes a command name and
  148. any `ArgumentParser` constructor arguments, and returns an `ArgumentParser` object
  149. that can be modified as usual.
  150. Example:
  151. sub_commands.js
  152. ```javascript
  153. #!/usr/bin/env node
  154. 'use strict';
  155. var ArgumentParser = require('../lib/argparse').ArgumentParser;
  156. var parser = new ArgumentParser({
  157. version: '0.0.1',
  158. addHelp:true,
  159. description: 'Argparse examples: sub-commands',
  160. });
  161. var subparsers = parser.addSubparsers({
  162. title:'subcommands',
  163. dest:"subcommand_name"
  164. });
  165. var bar = subparsers.addParser('c1', {addHelp:true});
  166. bar.addArgument(
  167. [ '-f', '--foo' ],
  168. {
  169. action: 'store',
  170. help: 'foo3 bar3'
  171. }
  172. );
  173. var bar = subparsers.addParser(
  174. 'c2',
  175. {aliases:['co'], addHelp:true}
  176. );
  177. bar.addArgument(
  178. [ '-b', '--bar' ],
  179. {
  180. action: 'store',
  181. type: 'int',
  182. help: 'foo3 bar3'
  183. }
  184. );
  185. var args = parser.parseArgs();
  186. console.dir(args);
  187. ```
  188. Details in [original sub-commands guide](http://docs.python.org/dev/library/argparse.html#sub-commands)
  189. Contributors
  190. ============
  191. - [Eugene Shkuropat](https://github.com/shkuropat)
  192. - [Paul Jacobson](https://github.com/hpaulj)
  193. [others](https://github.com/nodeca/argparse/graphs/contributors)
  194. License
  195. =======
  196. Copyright (c) 2012 [Vitaly Puzrin](https://github.com/puzrin).
  197. Released under the MIT license. See
  198. [LICENSE](https://github.com/nodeca/argparse/blob/master/LICENSE) for details.