Python argv函數(shù)簡(jiǎn)介

如果想對(duì)python腳步傳參數(shù),那么就需要命令行參數(shù)的支持了,這樣可以省的每次去改腳步了。
例如:

from sys import argv

pyname, one, two, three = argv
print("python file name is :", pyname)
print("The first word is :", one)
print("The second word is :", two)
print("The third word is :", three)

這個(gè)腳本運(yùn)行時(shí),如果直接輸入:

python ex13.py

返回結(jié)果如下:

Traceback (most recent call last):
  File "ex13.py", line 3, in <module>
    pyname, one, two, three = argv
ValueError: not enough values to unpack (expected 4, got 1)

因?yàn)橐笮枰?4 個(gè)參數(shù),實(shí)際只輸入了一個(gè)。
正確的運(yùn)行方式如下:

python ex13.py 1 3 hffhl#需連帶腳本名一共有 4 個(gè)參數(shù)

輸出結(jié)果如下:

python file name is : ex13.py
The first word is : 1
The second word is : 3
The third word is : hffhl

可以看到argv用法就是獲取在命令行執(zhí)行腳本時(shí)python命令后跟的所有參數(shù)

仔細(xì)思考一下,這里的argv 其實(shí)就是一個(gè)列表,具體看一下:

from sys import argv

pyname, one, two, three = argv
print("-------argv = ", argv)

輸入如下:

python ex13.py 1 3 hffhl

返回結(jié)果是:

-------argv =  ['ex13.py', '1', '3', 'hffhl']

argv其實(shí)就是一個(gè)列表,里邊的項(xiàng)為用戶(hù)輸入的參數(shù),關(guān)鍵就是要明白這參數(shù)是從程序外部輸入的,而非代碼本身的什么地方,要想看到它的效果就應(yīng)該將程序保存了,從外部來(lái)運(yùn)行程序并給出參數(shù)。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容