首页 > 解决方案 > 解析多个位置参数的问题

问题描述

我一定错过了一些非常明显的东西,但我终生无法发现它。

import argparse


def parse_args():
    parser = argparse.ArgumentParser(description="Copies selected files.")
    parser.add_argument(
        "-c", "--checksum", type=bool, default=False
    )
    parser.add_argument("source")
    parser.add_argument("target")
    return parser.parse_args()


def main():
    args = parse_args()
    print(args.checksum, args.source, args.target)


main()

>python file_proc.py source1 target1
False source1 target1

到现在为止还挺好。

>python file_proc.py -c source1 target1
usage: file_proc.py [-h] [-c CHECKSUM] source target
file_proc.py: error: the following arguments are required: target

现在,它为什么不输出True source1 target1?它一定就在我面前,但我需要另一双眼睛。

谢谢!

标签: pythonargumentsargparse

解决方案


您编码的方式基本上意味着,如果您正在传递-c,那么您还需要bool在 args 中传递 a 。

因此,您的声明:

>python file_proc.py source1 target1
False source1 target1

工作正常,因为你没有通过-c。所以,它打印出来了False

但是当你-c在命令行中传递时,它需要另一个变量来传递参数。所以这样做:

>python file_proc.py -c d source1 target1
True source1 target1

这意味着 abool作为参数传递,因此它打印True.


推荐阅读