python def 参数一直为false_python argparse传入布尔参数false不生效的解决

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值