Python获取命令行参数
sys.argv[]
?
包含命令行參數(shù)的字符串列表,通過下標(biāo)獲取參數(shù)。
?
例如:
?
?| #!/usr/bin/python # Filename: using_sys.py ?? import sys ?? print 'The command line arguments are:' for i in sys.argv: ????print i ?? print '\n\nThe PYTHONPATH is', sys.path, '\n'<BR><BR>print argv[1] |
?
?
?| argv[0]表示文件本身路徑。 當(dāng)然,agv[]也可存放多個(gè)值 |
?
getopt
?
用于抽出命令行選項(xiàng)和參數(shù),也就是sys.argv。命令行選項(xiàng)使得程序的參數(shù)更加靈活。支持短選項(xiàng)模式和長選項(xiàng)模式。
?
?
?
?| import getopt #python scriptname.py -f 'hello' --directory-prefix=/home -t --form??? at 'a' 'b' shortargs = 'f:t' longargs = ['directory-prefix=', 'format', '--f_long='] opts, args = getopt.getopt( sys.argv[1:], shortargs, longargs )<BR> |
?
getopt函數(shù)的格式是getopt.getopt ( [命令行參數(shù)列表], "短選項(xiàng)", [長選項(xiàng)列表] )
短選項(xiàng)名后的冒號(:)表示該選項(xiàng)必須有附加的參數(shù)。
長選項(xiàng)名后的等號(=)表示該選項(xiàng)必須有附加的參數(shù)。
返回opts和args。
?
opts是一個(gè)參數(shù)選項(xiàng)及其value的元組( ( '-f', 'hello'), ( '-t', '' ), ( '--format', '' ), ( '--directory-prefix', '/home' ) )
?
args是一個(gè)除去有用參數(shù)外其他的命令行輸入 ( 'a', 'b' )
?
然后遍歷opts便可以獲取所有的命令行選項(xiàng)及其對應(yīng)參數(shù)了。
?
遍歷opts可以獲取所有命令的選項(xiàng)及參數(shù),
?
?| for opt, val in opts: ????if opt in ( '-f', '--f_long' ): ????????pass ????if .... |
?
分析不同宣傳項(xiàng)參數(shù),做不同處理。 一般,選項(xiàng)參數(shù)列表會被打印作為幫助選項(xiàng)。
?
轉(zhuǎn)載于:https://www.cnblogs.com/secbook/archive/2012/11/26/2789256.html
總結(jié)
以上是生活随笔為你收集整理的Python获取命令行参数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 函数重载二义性:error C2668:
- 下一篇: python字典键值对转化为相应的变量名