【发布时间】:2021-02-18 01:06:37
【问题描述】:
我一定遗漏了一些非常明显的东西,但我终生无法发现它。
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?它一定就在我面前,但我需要另一双眼睛。
谢谢!
【问题讨论】:
-
type参数应该是一个函数,它将输入字符串转换为所需的值。如果您想将诸如“yes”或“no”之类的字符串解释为True/Falsebooleans,则必须自己编写。