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不生效的解決就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: