如何让Python argparse接收的布尔参数false参数生效?

2026-05-27 02:500阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计649个文字,预计阅读时间需要3分钟。

如何让Python argparse接收的布尔参数false参数生效?

在当代编码时,向Python程序传递bool参数,但无法传入False,无论传入True还是False,程序中都显示为True。以下是代码示例:

pythonparser.add_argument(--preprocess, type=bool, default=True, help='run prepare_dat')

跑代码时,在命令行给python程序传入bool参数,但无法传入False,无论传入True还是False,程序里面都是True。下面是代码:

parser.add_argument("--preprocess", type=bool, default=True, help='run prepare_data or not')

高端解决方案

使用可选参数store_true,将上述代码改为:

parse.add_argument("--preprocess", action='store_true', help='run prepare_data or not')

在命令行执行py文件时,不加--preprocess,默认传入的preprocess参数为False;

如果加--preprocess,则传入的是True。

阅读全文

本文共计649个文字,预计阅读时间需要3分钟。

如何让Python argparse接收的布尔参数false参数生效?

在当代编码时,向Python程序传递bool参数,但无法传入False,无论传入True还是False,程序中都显示为True。以下是代码示例:

pythonparser.add_argument(--preprocess, type=bool, default=True, help='run prepare_dat')

跑代码时,在命令行给python程序传入bool参数,但无法传入False,无论传入True还是False,程序里面都是True。下面是代码:

parser.add_argument("--preprocess", type=bool, default=True, help='run prepare_data or not')

高端解决方案

使用可选参数store_true,将上述代码改为:

parse.add_argument("--preprocess", action='store_true', help='run prepare_data or not')

在命令行执行py文件时,不加--preprocess,默认传入的preprocess参数为False;

如果加--preprocess,则传入的是True。

阅读全文