這篇文章主要為大家展示了python argparse傳入布爾參數(shù)false不生效怎么辦,內(nèi)容簡而易懂,希望大家可以學(xué)習(xí)一下,學(xué)習(xí)完之后肯定會(huì)有收獲的,下面讓小編帶大家一起來看看吧。

跑代碼時(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ù)類型來對我們接收的原始參數(shù)做處理,我們可以定義一個(gè)函數(shù)賦值給type參數(shù),用它對原始參數(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': '頻道添加失敗'}
當(dāng)前名稱:pythonargparse傳入布爾參數(shù)false不生效怎么辦-創(chuàng)新互聯(lián)
網(wǎng)站網(wǎng)址:http://www.jbt999.com/article18/jjhgp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供小程序開發(fā)、品牌網(wǎng)站制作、軟件開發(fā)、網(wǎng)站排名、網(wǎng)站內(nèi)鏈、網(wǎng)站設(shè)計(jì)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:[email protected]。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)