日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

Python?argparse中的action=store_true用法小結(jié)_python

作者:coder1479 ? 更新時(shí)間: 2023-04-24 編程語言

Python argparse中的action=store_true用法

前言

Python的命令行參數(shù)解析模塊學(xué)習(xí)。

示例

參數(shù)解析模塊支持action參數(shù),這個(gè)參數(shù)可以設(shè)置為’store_true’、‘store_false’、'store_const’等。
例如下面這行代碼,表示如果命令行參數(shù)中出現(xiàn)了"–PARAM_NAME",就把PARAM_NAME設(shè)置為True,否則為False。

parser.add_argument("--PARAM_NAME", action="store_true", help="HELP_INFO")

官方文檔

‘store_true’ and ‘store_false’ - These are special cases of ‘store_const’ used for storing the values True and False respectively. In addition, they create default values of False and True respectively. For example:

‘store_true’ 和 ‘store_false’ -這兩個(gè)是’store_const’的特例,分別用來設(shè)置True和False。另外,他們還會(huì)創(chuàng)建默認(rèn)值。

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='store_true')
>>> parser.add_argument('--bar', action='store_false')
>>> parser.add_argument('--baz', action='store_false')
>>> parser.parse_args('--foo --bar'.split())
Namespace(foo=True, bar=False, baz=True)

多了解一點(diǎn)兒

自定義

你可以通過給定一個(gè)Action的子類或其他實(shí)現(xiàn)了相同接口的對(duì)象,來指定一個(gè)任意的action
BooleanOptionalAction就是一個(gè)可以使用的action,它增加了布爾action特性,支持--foo--no-foo的形式。

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action=argparse.BooleanOptionalAction)
>>> parser.parse_args(['--no-foo'])
Namespace(foo=False)

小結(jié)

'--foo', action='store_true',可以很方便地實(shí)現(xiàn)布爾類型的參數(shù)。

思考

Python3 開始,很多內(nèi)置模塊都轉(zhuǎn)向了面向?qū)ο蠓妒健?br>對(duì)于早期開始使用Python的用戶來說,見到的代碼更多是面向過程或者是函數(shù)風(fēng)格的,例如,從Google開源的一些項(xiàng)目可以看到很多Python 2.x的代碼風(fēng)格。

補(bǔ)充:python庫Argparse中的可選參數(shù)設(shè)置 action=‘store_true‘ 的用法

store_true 是指帶觸發(fā)action時(shí)為真,不觸發(fā)則為假。

通俗講是指運(yùn)行程序是否帶參數(shù),看例子就明白了。

一、沒有default

import argparse
 
parser = argparse.ArgumentParser(description='test.py')
parser.add_argument('--cuda', type=bool, default=True,  help='use cuda')
parser.add_argument('--cpu',action='store_true',help='use cpu')
args = parser.parse_args()
 
print("cuda: ",args.cuda)
print("cpu: ",args.cpu)

如果運(yùn)行命令為:python test.py

則輸出為:

cuda: ?True
cpu: ?False

如果運(yùn)行命令為:python test.py --cpu

則輸出為:

cuda: ?True
cpu: ?True

二、有default

當(dāng)然 ‘store_true’ 也可以設(shè)置 default ,雖然這樣看起來很奇怪,也不好用。如:

parser.add_argument('--cpu',default=True,action='store_true',help='use cpu')
print("cpu: ",args.cpu)

default=True時(shí)運(yùn)行程序時(shí)加不加 “ --cpu ” 輸出都是 cpu: True

但default=False就不一樣了:

parser.add_argument('--cpu',default=False,action='store_true',help='use cpu')
print("cpu: ",args.cpu)

若運(yùn)行命令是 python test.py,則輸出 cpu: False

若運(yùn)行命令是 python test.py --cpu,則輸出 cpu: True

原文鏈接:https://blog.csdn.net/m0_48742971/article/details/124839044

欄目分類
最近更新