python argparse傳入布爾參數(shù)false不生效的解決
跑代碼時,在命令行給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文件時,不加--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文件時,不加--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文件時,不加--preprocess,默認(rèn)傳入的preprocess參數(shù)為True;
如果加--preprocess,則傳入的是False。
產(chǎn)生的原因和較Low的解決方案
猜測可能的原因是數(shù)據(jù)類型導(dǎo)致的,傳入的都是string類型,轉(zhuǎn)為bool型時,由于是非空字符串,所以轉(zhuǎn)為True。
從這個角度去更改的話,由于type參數(shù)接收的是callable的參數(shù)類型來對我們接收的原始參數(shù)做處理,我們可以定義一個函數(shù)賦值給type參數(shù),用它對原始參數(shù)做處理:
parser.add_argument('--preprocess', type=str2bool, default=’True’, help=’run prepare_data or not’)
下面定義這個函數(shù)將str類型轉(zhuǎn)換為bool型:
def str2bool(str):return True if str.lower() == ’true’ else False
補(bǔ)充知識: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傳入布爾參數(shù)false不生效的解決就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python中scrapy處理項目數(shù)據(jù)的實(shí)例分析2. Python中讀取文件名中的數(shù)字的實(shí)例詳解3. 在idea中為注釋標(biāo)記作者日期操作4. 通過Ajax方式綁定select選項數(shù)據(jù)的實(shí)例5. JSP頁面的靜態(tài)包含和動態(tài)包含使用方法6. ASP.Net Core對USB攝像頭進(jìn)行截圖7. ASP.NET MVC使用Boostrap實(shí)現(xiàn)產(chǎn)品展示、查詢、排序、分頁8. .net如何優(yōu)雅的使用EFCore實(shí)例詳解9. 使用AJAX(包含正則表達(dá)式)驗證用戶登錄的步驟10. ajax動態(tài)加載json數(shù)據(jù)并詳細(xì)解析
