问题解析多个位置参数

Issue parsing multiple positional arguments

我一定是遗漏了一些非常明显的东西,但我终究无法发现它。

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?它一定就在我面前,但我需要另一双眼睛。

谢谢!

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

因此你的声明:

>python file_proc.py source1 target1
False source1 target1

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

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

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

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

--checksum的参数声明意味着-c/--checksum之后传入了一个实际的布尔值。例如,--checksum yes 将“启用”校验和;由于 bool 解释字符串的方式,除空字符串之外的任何 参数的计算结果为 True.

使用 store_true/store_false action 定义一个 argument-less 标志,通过被提及来切换 on/off。

    parser.add_argument(
        "-c", "--checksum", action='store_true'
    )