如果想對(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ù)。