首页 > 脚本专栏 > 浏览文章

python argparse传入布尔参数false不生效的解决

(编辑:jimmy 日期: 2024/5/9 浏览:3 次 )

跑代码时,在命令行给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。

还可以将上述代码改为:

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

和 1 中表达的意思完全相同。

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

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

还可以将上述代码改为:

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

和 1 中表达的意思完全相反。

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

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

产生的原因和较Low的解决方案

猜测可能的原因是数据类型导致的,传入的都是string类型,转为bool型时,由于是非空字符串,所以转为True。

从这个角度去更改的话,由于type参数接收的是callable的参数类型来对我们接收的原始参数做处理,我们可以定义一个函数赋值给type参数,用它对原始参数做处理:

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

下面定义这个函数将str类型转换为bool型:

def str2bool(str):
return True if str.lower() == 'true' else False

补充知识:parser.add_argument验证格式

我就废话不多说了,还是直接看代码吧!

article_bp = Blueprint('article', __name__, url_prefix='/api')

api = Api(article_bp)
parser = reqparse.RequestParser()
parser.add_argument('name', type=str, help='必须填写名称', required=True)
channel_fields = {
 'id': fields.Integer,
 'cname': fields.String
}

class ChannelResource(Resource):
 def get(self):
 channels = Channel.query.all()
 return marshal(channels, channel_fields)

 def post(self):
 args = parser.parse_args()
 if args:
  channel = Channel()
  channel.cname = args.get('name')
  channel.save()
  return {'msg': '频道添加成功', 'channel': marshal(channel, channel_fields)}
 else:
  return {'msg': '频道添加失败'}

以上这篇python argparse传入布尔参数false不生效的解决就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

上一篇:解决python脚本中error: unrecognized arguments: True错误
下一篇:parser.add_argument中的action使用
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网