sys.argv[] 用法

sys.argv[]是用來獲取命令行輸入的參數的(參數和參數之間空格區分),sys.argv[0]表示代碼本身文件路徑,所以從參數1開始,表示獲取的參數了

例子0:

test.py

#-*-coding:utf-8-*-
from sys import argv

script,first,second,third = argv

print ("The script is called:{%s}"% script)
print ("Your first variable is:{%s}"% first)
print ("Your second variable is:{%s}"% second)
print ("Your third variable is:{%s}"% third)

運行結果:
這裏寫圖片描述

例子1:

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

os.system 是打開程序的命令,把這個代碼保存爲一個腳本文件,test.py在命令行中運行 test.py notepad就可以打開記事本了

例子2

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, # notice comma  分別輸出每行內容
    f.close()
# Script starts from here
if len(sys.argv) < 2:
    print 'No action specified.'
    sys.exit()
if sys.argv[1].startswith('--'):
    option = sys.argv[1][2:]
    # fetch sys.argv[1] but without the first two characters
    if option == 'version':  #當命令行參數爲-- version,顯示版本號
        print 'Version 1.2'
    elif option == 'help':  #當命令行參數爲--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 'Unknown option.'
    sys.exit()
else:
    for filename in sys.argv[1:]: #當參數爲文件名時,傳入readfile,讀出其內容
        readfile(filename)

保存程序爲test.py.運行一下:
1)
命令行帶參數運行:test.py
–version 輸出結果爲:version 1.2
2)
命令行帶參數運行:test.py
–help 輸出結果爲:This program prints files……
3)
在test.py目錄下,新建a.txt的記事本文件,內容爲:test argv;命令行帶參數運行:test.py a.txt,輸出結果爲a.txt文件內容:test argv,控制檯中輸入多個參數用空格區分。

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