python argparse傳入布爾參數(shù)false不生效的解決
跑代碼時(shí),在命令行給python程序傳入bool參數(shù),但無法傳入False,無論傳入True還是False,程序里面都是True。下面是代碼:
parser.add_argument('--preprocess', type=bool, default=True, help=’run prepare_data or not’)
高端解決方案
使用可選參數(shù)store_true,將上述代碼改為:
parse.add_argument('--preprocess', action=’store_true’, help=’run prepare_data or not’)
在命令行執(zhí)行py文件時(shí),不加--preprocess,默認(rèn)傳入的preprocess參數(shù)為False;
如果加--preprocess,則傳入的是True。
還可以將上述代碼改為:
parse.add_argument('--preprocess', default=’False’, action=’store_true’, help=’run prepare_data or not’)
和 1 中表達(dá)的意思完全相同。
在命令行執(zhí)行py文件時(shí),不加--preprocess,默認(rèn)傳入的preprocess參數(shù)為False;
如果加--preprocess,則傳入的是True。
還可以將上述代碼改為:
parse.add_argument('--preprocess', default=’True’, action=’store_true’, help=’run prepare_data or not’)
和 1 中表達(dá)的意思完全相反。
在命令行執(zhí)行py文件時(shí),不加--preprocess,默認(rèn)傳入的preprocess參數(shù)為True;
如果加--preprocess,則傳入的是False。
產(chǎn)生的原因和較Low的解決方案
猜測可能的原因是數(shù)據(jù)類型導(dǎo)致的,傳入的都是string類型,轉(zhuǎn)為bool型時(shí),由于是非空字符串,所以轉(zhuǎn)為True。
從這個(gè)角度去更改的話,由于type參數(shù)接收的是callable的參數(shù)類型來對(duì)我們接收的原始參數(shù)做處理,我們可以定義一個(gè)函數(shù)賦值給type參數(shù),用它對(duì)原始參數(shù)做處理:
parser.add_argument('--preprocess', type=str2bool, default=’True’, help=’run prepare_data or not’)
下面定義這個(gè)函數(shù)將str類型轉(zhuǎn)換為bool型:
def str2bool(str):return True if str.lower() == ’true’ else False
補(bǔ)充知識(shí):parser.add_argument驗(yàn)證格式
我就廢話不多說了,還是直接看代碼吧!
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傳入布爾參數(shù)false不生效的解決就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. XML在語音合成中的應(yīng)用2. HTTP協(xié)議常用的請(qǐng)求頭和響應(yīng)頭響應(yīng)詳解說明(學(xué)習(xí))3. 不要在HTML中濫用div4. ASP將數(shù)字轉(zhuǎn)中文數(shù)字(大寫金額)的函數(shù)5. .NET Framework各版本(.NET2.0 3.0 3.5 4.0)區(qū)別6. jscript與vbscript 操作XML元素屬性的代碼7. HTML5實(shí)戰(zhàn)與剖析之觸摸事件(touchstart、touchmove和touchend)8. php使用正則驗(yàn)證密碼字段的復(fù)雜強(qiáng)度原理詳細(xì)講解 原創(chuàng)9. ASP基礎(chǔ)入門第四篇(腳本變量、函數(shù)、過程和條件語句)10. XML入門的常見問題(三)
