Argparse,一个参数有两个值

问题描述 投票:0回答:2

现在我的脚本通过以下方式调用:

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] 不起作用

python command-line argparse
2个回答
39
投票

使用

nargs=2

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

args = parser.parse_args()

newfile, oldfile = args.compare

如果您运行 metavar=('newfile', 'oldfile')

,还添加 
resylter.py -h
 可以改进帮助文本。


0
投票

nargs = '*'

一起工作

我做了以下事情:

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

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

现在可以使用了

© www.soinside.com 2019 - 2024. All rights reserved.