跳轉到內容

Python 程式設計入門/Python 程式設計 - 命令列引數

來自華夏公益教科書,開放的書籍,開放的世界

8. 命令列引數

[編輯 | 編輯原始碼]

需要匯入 sys 模組才能從 Python 直譯器讀取命令列引數。

以下是一個示例。

   >>> import sys
   >>> print 'The number of arguments at command line are ', len(sys.argv)
   The number of arguments at command line are  1
   No.  0 Arugment  C:/Users/Desktop/Projects/Upwork/firstworkspace.py
   >>>C:\Users\Desktop\Projects\Upwork>python second.py
   The number of arguments at command line are  1
   And the arguments are Argument List: ['second.py']
   >>>C:\Users\ Desktop\Projects\Upwork>python second.py 1 2 3 4
   The number of arguments at command line are  5
   And the arguments are Argument List: ['second.py', '1', '2', '3', '4']
   >>> count=0
   for b in sys.argv:
       print 'No. ', count, 'Arugment ', b
       count+=1
   >>>C:\Users\Desktop\Projects\Upwork>python second.py 1 2 3 4
   The number of arguments at command line are  5
   No.  0 Arugment  second.py
   No.  0 Arugment  1
   No.  0 Arugment  2
   No.  0 Arugment  3
   No.  0 Arugment  4
   C:\Users\Desktop\Projects\Upwork>python second.py 1 2 3 4
   The number of arguments at command line are  5
   No.  0 Arugment  second.py
   No.  1 Arugment  1
   No.  2 Arugment  2
   No.  3 Arugment  3
   No.  4 Arugment  4
   C:\Users\Desktop\Projects\Upwork
華夏公益教科書