Python 编程入门/Python 编程 - 命令行参数
外观
需要导入 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