您好,登錄后才能下訂單哦!
參考原文:
Python模塊之命令行參數(shù)解析 - 每天進(jìn)步一點(diǎn)點(diǎn)?。?! - 博客園 https://www.cnblogs.com/madsnotes/articles/5687079.html
python getopt使用 - tianzhu123的專(zhuān)欄 - CSDN博客 https://blog.csdn.net/tianzhu123/article/details/7655499
在運(yùn)行程序時(shí),可能需要根據(jù)不同的條件,輸入不同的命令行選項(xiàng)來(lái)實(shí)現(xiàn)不同的功能。這時(shí)候就用到getopt模塊了。
# 參數(shù)args一般是sys.argv[1:],sys.argv[1:] 過(guò)濾掉第一個(gè)參數(shù)(它是腳本名稱(chēng),不是參數(shù)的一部分)
# shortopts :短格式 (-) ,后面沒(méi)有冒號(hào),表示后面不帶參數(shù),后面有冒號(hào)表示后面需要參數(shù)
# longopts :長(zhǎng)格式(--) ,后面沒(méi)有等號(hào)=,表示后面不帶參數(shù),有=,表示后面需要參數(shù)
# 使用方法:opts, args = getopt.getopt(args, shortopts, longopts = [])
options,args = getopt.getopt(sys.argv[1:],"hp:i:",["help","ip=","port="])
import getopt
import sys
def usage():
'提示命令行參數(shù)'
print(
'''
Usage:sys.args[0] [option]
-h or --help:顯示幫助信息
-i or --ip:ip
-p or --port:port
'''
)
def main():
if len(sys.argv) == 1:
usage()
sys.exit()
try:
# sys.argv[1:] 過(guò)濾掉第一個(gè)參數(shù)(它是腳本名稱(chēng),不是參數(shù)的一部分)
# 返回值 options 是個(gè)包含元組的列表,每個(gè)元組是分析出來(lái)的格式信息,比如 [('-i','127.0.0.1'),('-p','80')]
# args 是個(gè)列表,包含那些沒(méi)有‘-’或‘--’的參數(shù),比如:['55','66']
options, args = getopt.getopt(sys.argv[1:], "hp:i:", ["help", "ip=", "port="])
except getopt.GetoptError:
print("argv error,please input")
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)
print('argv is----', args)
if __name__ == "__main__":
main()
命令行中輸入:python test.py -h -i 127.0.0.1 --port=80 55 66 -h
結(jié)果:
是不是很簡(jiǎn)單!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。