溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

一文看懂命令行參數(shù)的用法——Python中的getopt神器

發(fā)布時(shí)間:2020-07-24 16:52:16 來(lái)源:網(wǎng)絡(luò) 閱讀:484 作者:mb5c9f0bd46ed07 欄目:編程語(yǔ)言

一文看懂命令行參數(shù)的用法——Python中的getopt神器


參考原文:
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模塊了。

1、短格式和長(zhǎng)格式

# 參數(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="])

2、options和args

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()

3、測(cè)試

命令行中輸入:
python test.py -h -i 127.0.0.1 --port=80 55 66 -h

結(jié)果:
一文看懂命令行參數(shù)的用法——Python中的getopt神器

是不是很簡(jiǎn)單!

向AI問(wèn)一下細(xì)節(jié)

免責(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)容。

AI