一个参数有两个值的 Argparse

Argparse with two values for one argument

现在我的脚本调用通过:

python resylter.py -n *newfile* -o *oldfile*

代码如下:

parser.add_argument('-n', '--newfile', help='Uses only with -o argument. Compares inputed OLD (-o) file with previous run results with NEW(-n) output.xml file with actual run results')
parser.add_argument('-o', '--oldfile', help='Uses only with -n argument. Compares inputed OLD (-o)  file with previous run results with NEW(-n) output.xml file with actual run results')

和一些动作

我如何编辑它才能像这样使用?:

python resylter.py -n *newfile* *oldfile*

sys.argv[-1] 无效

nargs = '*'

合作

我做了以下操作:

parser.add_argument('-c', '--compare', nargs = '*')

_newfile_ = _args_.compare[0]
_oldfile_ = _args_.compare[1]

现在可以使用了

使用nargs=2:

parser.add_argument(
    '-c',
    '--compare',
    nargs=2,
    metavar=('newfile', 'oldfile'),
    help='Compares previous run results in oldfile with actual run results in newfile.',
    )

args = parser.parse_args()

newfile, oldfile = args.compare

如果您 运行 resylter.py -h.

,还可以添加 metavar=('newfile', 'oldfile') 改进帮助文本