python - 解析多个位置参数的问题
问题描述
我一定错过了一些非常明显的东西,但我终生无法发现它。
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
,那么您还需要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
.
推荐阅读
- python - 自定义解释器提示后python解释器中的错误缩进
- sql - SQL Server:忽略 AVG NULL 值
- list - 没有为类 'Map<>' 定义 getter 为 Map 列出 getter
- android - 找不到符号类数据绑定 impl
- jpa - 如何使用 EclipseLink 从 JPQL 查询返回键/值对映射列表?
- python - 匹配两个节点并保持其他各自节点之间的路径networkx
- javascript - 在 JavaScript 中按名称而不是 id 单击元素
- moodle - 拥有 30000 个用户的 Moodle 的服务器硬件
- python-3.x - 如何从 python 中的列表创建列表?
- python - AttributeError:“布尔”对象没有属性“按钮”