Python:sys.argv[]用法

 sys.argv[]是用來獲取命令行參數的,sys.argv[0]表示代碼本身文件路徑,所以參數從1開始,以下兩個例子說明:
1.使用sys.argv[]的一簡單實例:

1
2
import sys, os
os.system(sys.argv[])
 




這個例子os.system接受命令行參數,運行參數指令,保存爲sample1.py,命令行帶參數運行sample1.py notepad,將打開記事本程序。
2.這個例子是簡明python教程上的,明白它之後你就明白sys.argv[]了:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import sys
def readfile(filename):
''' Print a file to the standard output. '''
f = file(filename)
while True:
line = f.readline()
if len(line) == 0:
break
print line
f.close()

#Script starts from here
if len(sys.argv) < 2:
print ' NO action specified.'
sys.exit()

if sys.argv[1].startwith('--'):
option = sys.argv[1][2:]
if option == 'version':
print ' version 1.2 '
elif option == 'help':
print '''This program prints files to the standard output.
Any number of files can be specified.
Options include:
--version : Prints the version number
--help : Display this help'''
else:
print 'Unknow option.'
else:
for filename in sys.argv[1:]:
readfile(filename)
 




保存爲sample2.py,我們驗證一下:
1)命令行帶參數運行:sample.py --version 輸出結果爲:version 1.2
2)命令行帶參數運行:sample.py --help 輸出結果爲:This program prints files……
3)與sample.py同一目錄下,新建a.txt的記事本文件,內容爲:test argv;
命令行帶參數運行:sample.py a.txt,輸出結果爲a.txt文件內容:test argv,
這裏也可以多帶幾個參數,程序會先後輸出參數文件內容。

 

root@scpman:/usr/python/socket/unit1# cat a.py
#!/usr/bin/env python
import sys, os
print sys.argv[0],sys.argv[1],sys.argv[2]

root@scpman:/usr/python/socket/unit1# ./a.py --version help
./a.py --version help
root@scpman:/usr/python/socket/unit1# 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章