-
當(dāng)前位置:首頁(yè) > 創(chuàng)意學(xué)院 > 營(yíng)銷推廣 > 專題列表 > 正文
python getopt模塊(python getpass模塊)
大家好!今天讓創(chuàng)意嶺的小編來(lái)大家介紹下關(guān)于python getopt模塊的問(wèn)題,以下是小編對(duì)此問(wèn)題的歸納整理,讓我們一起來(lái)看看吧。
開(kāi)始之前先推薦一個(gè)非常厲害的Ai人工智能工具,一鍵生成原創(chuàng)文章、方案、文案、工作計(jì)劃、工作報(bào)告、論文、代碼、作文、做題和對(duì)話答疑等等
只需要輸入關(guān)鍵詞,就能返回你想要的內(nèi)容,有小程序、在線網(wǎng)頁(yè)版、PC客戶端和批量生成器
問(wèn)友Ai官網(wǎng):https://ai.de1919.com。
本文目錄:
python里argparse模塊和getopt模塊的區(qū)別
argparse是用于腳本帶參數(shù)使用的,假設(shè)你有如下腳本名為prog.py,內(nèi)容如下:
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print args.accumulate(args.integers)
你在控制臺(tái)終端上輸入python prog.py -h即可獲得幫助說(shuō)明
$ python prog.py -h
usage: prog.py [-h] [--sum] N [N ...]
Process some integers.
positional arguments:
N an integer for the accumulator
optional arguments:
-h, --help show this help message and exit
--sum sum the integers (default: find the max)
在再終端帶參數(shù)輸入命令行中,即可求得值
$ python prog.py 1 2 3 4
4
$ python prog.py 1 2 3 4 --sum
10
python中的from getopt import getopt有什么作用呢
from getopt import getopt就是從getopt包里導(dǎo)入getopt模塊,也可以直接import getopt,getopt主要是python用來(lái)獲取命令行參數(shù)用的,如:python test.py -y 23,你需要傳一個(gè)參數(shù)y是就可以用getopt
import?getopt,systry:
????opts,?args?=?getopt.getopt(sys.argv[1:],?"ho:",?["help",?"y="])
except?getopt.GetoptError:
????#?print?help?information?and?exit:
具體可以參考下API文檔
python getopt有什么用
python中 getopt 模塊,該模塊是專門(mén)用來(lái)處理命令行參數(shù)的
函數(shù)getopt(args, shortopts, longopts = [])
參數(shù)args一般是sys.argv[1:]
shortopts 短格式 (-)
longopts 長(zhǎng)格式(--)
命令行中輸入:
python test.py -i 127.0.0.1 -p 80 55 66
python test.py --ip=127.0.0.1 --port=80 55 66
下面的代碼:
try:
options,args = getopt.getopt(sys.argv[1:],"hp:i:",["help","ip=","port="])
except getopt.GetoptError:
sys.exit()
for name,value in options:
if name in ("-h","--help"):
usage()
if name in ("-i","--ip"):
print 'ip is----',value
if name in ("-p","--port")print 'port is----',value
options,args = getopt.getopt(sys.argv[1:],"hp:i:",["help","ip=","port="])
“hp:i:”
短格式 --- h 后面沒(méi)有冒號(hào):表示后面不帶參數(shù),p:和 i:后面有冒號(hào)表示后面需要參數(shù)
["help","ip=","port="]
長(zhǎng)格式 --- help后面沒(méi)有等號(hào)=,表示后面不帶參數(shù),其他三個(gè)有=,表示后面需要參數(shù)
返回值 options 是個(gè)包含元祖的列表,每個(gè)元祖是分析出來(lái)的格式信息,比如 [('-i','127.0.0.1'),('-p','80')] ;
args 是個(gè)列表,包含那些沒(méi)有‘-’或‘--’的參數(shù),比如:['55','66']
注意:定義命令行參數(shù)時(shí),要先定義帶'-'選項(xiàng)的參數(shù),再定義沒(méi)有‘-’的參數(shù)
以上就是關(guān)于python getopt模塊相關(guān)問(wèn)題的回答。希望能幫到你,如有更多相關(guān)問(wèn)題,您也可以聯(lián)系我們的客服進(jìn)行咨詢,客服也會(huì)為您講解更多精彩的知識(shí)和內(nèi)容。
推薦閱讀:
python依據(jù)模板生成word文檔(python依據(jù)模板生成word文件)
熊貓vi設(shè)計(jì)手冊(cè)(熊貓?jiān)O(shè)計(jì)網(wǎng)站)
中國(guó)照明十大名牌(開(kāi)關(guān)插座十大排名)