argparse
用于node.js的CLI参数解析器 sub-commands 支持。巨蟒港 argparse (版本 3.14.6).
与原不同。
- JS不支持关键字参数。
- 传递选项:
new ArgumentParser({ description: 'example', add_help: true })。
- 传递选项:
- JS没有python的类型
int,float,……- 使用字符串类型的名称:
.add_argument('-b', { type: 'int', help: 'help' })。
- 使用字符串类型的名称:
%r格式说明符的用法require('util').inspect()。
的完整列表 与Python的区别。 从v2升级的用户应该阅读 迁移指南。
例子
下面的代码是一个JS程序,它接受一个整数列表,并产生总和或最大值:
const { ArgumentParser } = require('argparse')
const parser = new ArgumentParser({ description: 'Process some integers.' })
let sum = ints => ints.reduce((a, b) => a + b)
let max = ints => ints.reduce((a, b) => a > b ? a : b)
parser.add_argument('integers', { metavar: 'N', type: 'int', nargs: '+',
help: 'an integer for the accumulator' })
parser.add_argument('--sum', { dest: 'accumulate', action: 'store_const',
const: sum, default: max,
help: 'sum the integers (default: find the max)' });
let args = parser.parse_args()
console.log(args.accumulate(args.integers))
假设上面的JS代码被保存到一个名为prog.js的文件中,它可以在命令行运行并提供有用的帮助信息:
$ node prog.js -h
usage: prog.js [-h] [--sum] N [N ...]
Process some integers.
positional arguments:
N an integer for the accumulator
options:
-h, --help show this help message and exit
--sum sum the integers (default: find the max)
当使用适当的参数运行时,它会打印命令行整数的总和或最大值:
$ node prog.js 1 2 3 4
4
$ node prog.js 1 2 3 4 --sum
10
如果传入无效参数,则会发出错误:
$ node prog.js a b c
usage: prog.js [-h] [--sum] N [N ...]
prog.js: error: argument N: invalid 'int' value: 'a'
这是一个从Python移植过来的例子。你可以找到详细的解释 在这里。
API文档
由于这是一个分歧最小的移植,因此没有单独的文档。 请使用原版,并注明差异。
- 原始文档。
- 最初的教程。
- 与Python的区别。
- 从v2迁移到v3。