【问题标题】:Argparse with two values for one argument一个参数有两个值的 argparse
【发布时间】:2016-05-01 13:03:59
【问题描述】:

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

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

【问题讨论】:

  • 我不认为这会有用。我只是将oldfile 保留为positional argument(即parser.add_argument('oldfile', ...)

标签: python command-line argparse


【解决方案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') 改进帮助文本。

【讨论】:

    【解决方案2】:

    nargs = '*'一起工作

    我做了以下:

    parser.add_argument('-c', '--compare', nargs = '*')
    
    _newfile_ = _args_.compare[0]
    _oldfile_ = _args_.compare[1]
    

    现在可以使用了

    【讨论】:

    • nargs='*' 中的星号表示零个或多个参数(如在正则表达式中),在这种情况下没有意义。
    猜你喜欢
    • 2019-01-28
    • 2018-12-25
    • 2012-06-24
    • 2021-12-18
    • 2015-07-25
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多