2015-09-19 71 views
6

我沒有得到期望的這個程序的輸出?如何在Python 3.x中傳遞命令行參數?

from sys import argv 

script, first, second, third = argv 

print ("The script is called:", script) 
print ("Your first variable is:", first) 
print ("Your second variable is:", second) 
print ("Your third variable is:", third) 

如何使用cmd傳遞這些參數?

回答

9

你這樣稱呼它

python program.py a1 b2 c3 

它輸出

The script is called: /home/sophia/program.py 
Your first variable is: a1 
Your second variable is: b2 
Your third variable is: c3 

sys.argv包含字符串列表,每個對應一個命令行參數。第一個始終是腳本的文件名;其他是可選參數,按照在shell中鍵入的順序排列。

請注意,您提供的代碼正常工作只有當您傳遞正確的三個參數由於元組解包。

如果要編寫處理大量參數的程序,請參閱文檔sys.argv以及檢查argparse module文檔。