当前位置:首页 » python教程 » 正文

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

看: 868次  时间:2020-07-17  分类 : python教程

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

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!