arg

Simple argument parsing
授权协议 MIT License
开发语言 JavaScript
所属分类 应用工具、 终端/远程登录
软件类型 开源软件
地区 不详
投 递 者 栾弘新
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

Arg

arg is an unopinionated, no-frills CLI argument parser.

Installation

npm install arg

Usage

arg() takes either 1 or 2 arguments:

  1. Command line specification object (see below)
  2. Parse options (Optional, defaults to {permissive: false, argv: process.argv.slice(2), stopAtPositional: false})

It returns an object with any values present on the command-line (missing options are thusmissing from the resulting object). Arg performs no validation/requirement checking - weleave that up to the application.

All parameters that aren't consumed by options (commonly referred to as "extra" parameters)are added to result._, which is always an array (even if no extra parameters are passed,in which case an empty array is returned).

const arg = require('arg');

// `options` is an optional parameter
const args = arg(
	spec,
	(options = { permissive: false, argv: process.argv.slice(2) })
);

For example:

$ node ./hello.js --verbose -vvv --port=1234 -n 'My name' foo bar --tag qux --tag=qix -- --foobar
// hello.js
const arg = require('arg');

const args = arg({
	// Types
	'--help': Boolean,
	'--version': Boolean,
	'--verbose': arg.COUNT, // Counts the number of times --verbose is passed
	'--port': Number, // --port <number> or --port=<number>
	'--name': String, // --name <string> or --name=<string>
	'--tag': [String], // --tag <string> or --tag=<string>

	// Aliases
	'-v': '--verbose',
	'-n': '--name', // -n <string>; result is stored in --name
	'--label': '--name' // --label <string> or --label=<string>;
	//     result is stored in --name
});

console.log(args);
/*
{
	_: ["foo", "bar", "--foobar"],
	'--port': 1234,
	'--verbose': 4,
	'--name': "My name",
	'--tag': ["qux", "qix"]
}
*/

The values for each key=>value pair is either a type (function or [function]) or a string (indicating an alias).

  • In the case of a function, the string value of the argument's value is passed to it,and the return value is used as the ultimate value.

  • In the case of an array, the only element must be a type function. Array types indicatethat the argument may be passed multiple times, and as such the resulting value in the returnedobject is an array with all of the values that were passed using the specified flag.

  • In the case of a string, an alias is established. If a flag is passed that matches the key,then the value is substituted in its place.

Type functions are passed three arguments:

  1. The parameter value (always a string)
  2. The parameter name (e.g. --label)
  3. The previous value for the destination (useful for reduce-like operations or for supporting -v multiple times, etc.)

This means the built-in String, Number, and Boolean type constructors "just work" as type functions.

Note that Boolean and [Boolean] have special treatment - an option argument is not consumed or passed, but instead true isreturned. These options are called "flags".

For custom handlers that wish to behave as flags, you may pass the function through arg.flag():

const arg = require('arg');

const argv = [
	'--foo',
	'bar',
	'-ff',
	'baz',
	'--foo',
	'--foo',
	'qux',
	'-fff',
	'qix'
];

function myHandler(value, argName, previousValue) {
	/* `value` is always `true` */
	return 'na ' + (previousValue || 'batman!');
}

const args = arg(
	{
		'--foo': arg.flag(myHandler),
		'-f': '--foo'
	},
	{
		argv
	}
);

console.log(args);
/*
{
	_: ['bar', 'baz', 'qux', 'qix'],
	'--foo': 'na na na na na na na na batman!'
}
*/

As well, arg supplies a helper argument handler called arg.COUNT, which equivalent to a [Boolean] argument's .lengthproperty - effectively counting the number of times the boolean flag, denoted by the key, is passed on the command line..For example, this is how you could implement ssh's multiple levels of verbosity (-vvvv being the most verbose).

const arg = require('arg');

const argv = ['-AAAA', '-BBBB'];

const args = arg(
	{
		'-A': arg.COUNT,
		'-B': [Boolean]
	},
	{
		argv
	}
);

console.log(args);
/*
{
	_: [],
	'-A': 4,
	'-B': [true, true, true, true]
}
*/

Options

If a second parameter is specified and is an object, it specifies parsing options to modify the behavior of arg().

argv

If you have already sliced or generated a number of raw arguments to be parsed (as opposed to letting argslice them from process.argv) you may specify them in the argv option.

For example:

const args = arg(
	{
		'--foo': String
	},
	{
		argv: ['hello', '--foo', 'world']
	}
);

results in:

const args = {
	_: ['hello'],
	'--foo': 'world'
};

permissive

When permissive set to true, arg will push any unknown argumentsonto the "extra" argument array (result._) instead of throwing an error aboutan unknown flag.

For example:

const arg = require('arg');

const argv = [
	'--foo',
	'hello',
	'--qux',
	'qix',
	'--bar',
	'12345',
	'hello again'
];

const args = arg(
	{
		'--foo': String,
		'--bar': Number
	},
	{
		argv,
		permissive: true
	}
);

results in:

const args = {
	_: ['--qux', 'qix', 'hello again'],
	'--foo': 'hello',
	'--bar': 12345
};

stopAtPositional

When stopAtPositional is set to true, arg will halt parsing at the firstpositional argument.

For example:

const arg = require('arg');

const argv = ['--foo', 'hello', '--bar'];

const args = arg(
	{
		'--foo': Boolean,
		'--bar': Boolean
	},
	{
		argv,
		stopAtPositional: true
	}
);

results in:

const args = {
	_: ['hello', '--bar'],
	'--foo': true
};

Errors

Some errors that arg throws provide a .code property in order to aid in recovering from user error, or todifferentiate between user error and developer error (bug).

ARG_UNKNOWN_OPTION

If an unknown option (not defined in the spec object) is passed, an error with code ARG_UNKNOWN_OPTION will be thrown:

// cli.js
try {
	require('arg')({ '--hi': String });
} catch (err) {
	if (err.code === 'ARG_UNKNOWN_OPTION') {
		console.log(err.message);
	} else {
		throw err;
	}
}
node cli.js --extraneous true
Unknown or unexpected option: --extraneous

FAQ

A few questions and answers that have been asked before:

How do I require an argument with arg?

Do the assertion yourself, such as:

const args = arg({ '--name': String });

if (!args['--name']) throw new Error('missing required argument: --name');

License

Released under the MIT License.

  • arg    是变元(即自变量argument)的英文缩写。 arg min 就是使后面这个式子达到最小值时的变量的取值 arg max 就是使后面这个式子达到最大值时的变量的取值 例如 函数F(x,y): arg  min F(x,y)就是指当F(x,y)取得最小值时,变量x,y的取值 arg  max F(x,y)就是指当F(x,y)取得最大值时,变量x,y的取值

  • arg: argument of a complex number 复数的辐角 表示使目标函数取最小值时的变量值 偶再补充一下,和u范围闭不闭没什么关系,其实我的意思是右面的式子不一定有意义,当u可取无限个值时,它可能无限逼近一个极小值,但永远取不到该极小值 例如: z = r*(cosθ + i sinθ) r是z的模,即:r = |z|; θ是z的辐角,记作:θ = arg(z

  • 我知道arc是三角函数中的,代表反三角函数,那么arg呢?好象与虚数有关,那. 复数的幅角 举个例子:z = r*(cosθ + i sinθ) r是z的模,即:r = |z|; θ是z的辐角,记作:θ = arg(z); arg:argumentofacomplexnumber复数的辐角 例如:z=r*(cosθ+isinθ) r是z的模,即:r=|z|; θ是z的辐角,记作:θ=arg(z)

  • np.argmax是用于取得数组中每一行或者每一列的的最大值。常用于机器学习中获取分类结果、计算精确度等。 函数:numpy.argmax(array, axis) array:代表输入数组;axis:代表对array取行(axis=0)或列(axis=1)的最大值。 一、一维数组的用法 x = np.arange(12) # [ 0 1 2 3 4

  • 数学中 arg min的意思:arg min 就是使后面这个式子达到最小值时的x,t的取值。1、其中arg min是元素(变元)的英文缩写。比如:函数 cos(x) 在 ±π、±3π、±5π、……处. arg 是参数的意思,一般从命令行输入,min是最小的意思。合起来就是在命令行输入最少的参数个数 使 x的2范数 值最小 的 x的值2范数 二范数 矩阵a的2范数就是 a的转置矩阵乘以a特征根 最大

  • numpy中argmax、argmin的用法 1.argmax,argmin的作用 argmax: 返回每行或每列的最大值所在下标索引 argmin: 返回每行或每列的最下值所在下标索引 参数 axis=0 表示垂直方向,axis=1表示水平方向。(由于个人的思维定势,老认为1是垂直方向,所以遇到numpy的axis方向不管三七二十一,认为是反的,先把axis=1当作水平方向,再看axis=0)

  • constructor-arg子标签作用: 指定创建类对象时使用哪个构造函数,每一对或者每一个constructor-arg子标签配置一个参数列表中的参数值;如果不配置子标签,则默认使用无参构造方法实例化对象(即该标签通过指定参数列表,对应地来指定多个构造方法中一个具体的构造方法)。 综述 constructor-arg标签属性: name属性:通过参数名找到参数列表中对应参数 index属性:通

  •   无论何种编程语言或脚本中,都不可避免的会应用到变量。dockerfile中使用ARG来定义变量,本文来对ARG指令定义变量进行解析。   ARG 语法: ARG <name>[=<default value>]   ARG 语义:   · ARG指令用于定义一个变量,可以使用--build-arg <varname>=<value>标志在构建时通过docker build命令传递给构建器。

  • tf.argmax(data, axis=None) 用tensorflow 做 mnist分类时,用到这个接口,于是就研究了下这个接口的用法: 如果是一维数组呢? data = tf.constant([1,2,3]) with tf.Session() as sess: print(sess.run(tf.argmax(data, 0))) #轴默认为0 print(sess.run(t

  • jq的--arg参数用法 --arg 这是最基本的参数 --arg name value 含义是定义变量$name的值为"value"。 注意这里的value是安装字符串处理的,所以即使是数字值,也是数字串,例如--arg v 123,那么$v=="123"。 举个例子: $ echo '{"AA":"aa","BB":"bb"}' | jq --arg v XX '.BB=$v' { "AA":

  • 1、Qstring QString::arg() 用字符串变量一次替换字符串中最小数值 QString i = "a"; // current file's number QString total = "10"; // number of files to process QString fileName = "unkown"; //

  • numpy.argmin(a, axis=None, out=None) numpy.argmax(a, axis=None, out=None) 以argmin为例。 1. 各参数值 a : 输入数组 axis:none、0、1、2… 默认值:数组展平。否则按照指定的axis方向。如axis=0。 out : 输出结果 返回值: 下标组成的数组,返回axis轴上最小值的索引构成的矩阵。 其sha

  • def argmax(a, axis=None, out=None, *, keepdims=np._NoValue): """ Returns the indices of the maximum values along an axis. Parameters ---------- a : array_like Input array.

  • 一、在latex环境中的argmin argmax 上下标 下标\mathop{\arg\max}\_{param}: arg ⁡ max ⁡ p a r a m \mathop{\arg\max}\limits_{param} paramargmax​ 上标\mathop{\arg\min}\^{param}: arg ⁡ min ⁡ p a r a m \mathop{\arg\min}\li

  • argmax函数:torch.argmax(input, dim=None, keepdim=False) 返回指定维度最大值的序号,dim给定的定义是:the demention to reduce,就是把dim这个维度,变成这个维度的最大值的index。 1)dim表示不同维度。特别的在dim=0表示二维矩阵中的列,dim=1在二维矩阵中的行。广泛的来说,我们不管一个矩阵是几维的,比如一个矩阵

相关阅读

相关文章

相关问答

相关文档