2014年7月25日 星期五

python sys.argv[]用法


常看到python中出現sys.argv[]這東西
找了些資料總算理解了
紀錄一下備忘

sys.argv[]是python獲取命令列參數的方法
譬如我們在terminal中會輸入的指令
ls -a
-a就是命令列參數
sys.argv[0] 代表了文件的檔案名稱本身
意思就是ls
sys.argv[1] 就代表了-a

以下是參考網路的範例並修改成容易理解的方式




# -*- coding: utf-8 -*-

import sys>



>#建立一個讀取檔案的function能將檔案內容print出來

def readfile(filename): 

 '''read file and print'''

 f = file(filename)

 while True:

  line = f.readline()

  if len(line) == 0:

   break

  print line, 

 f.close()

 

#開始對sys.argv下定義

if len(sys.argv) < 2: #len小於2也就是不帶參數啦

 print 'no argument'

 sys.exit()

if sys.argv[1].startswith('--'):

 option = sys.argv[1][2:] # 取出sys.argv[1]的數值但是忽略掉'--'這兩個字元

 if option == 'version': 

  print 'Version 1.2.3'

 elif option == 'help':

  print 'help documention'

 else:

  print 'only --version --help can be used'

  sys.exit()

else:

 for filename in sys.argv[1:]: #檔案名稱於參數位置時讀取檔案

  readfile(filename)



"""

此檔案名稱為readfile.py

則可以用readfile.py --version來查詢版號

readfile.py --help來查詢help文件

readfile.py readme.txt 可以執行function

"""

8 則留言:

  1. https://www.royaltykitten.com/sphynx-kittens-for-sale
    https://www.royaltykitten.com/sphynx-kittens-available/
    https://www.royaltykitten.com/sphynx-for-sale/
    https://www.royaltykitten.com/black-sphynx-kitten/
    https://www.royaltykitten.com/sphynx-kitten-near-me

    回覆刪除
  2. How are Sphynx cats with other pets?
    This is hard to answer. Generally, as a breed and given how affectionate they are I would say you have a better chance of a Sphynx cat getting along with other pets than a different breed of cat. But then each one is different and may or may not like any given pet or person. https://www.royaltykitten.com/
    sphynx cats for sale
    They definitely do not like to be alone, that was one of the reasons we got two. So it is always good for them to have a buddy if you are going to be away at work all day.
    https://www.chihuahuapuppiesforsale1.com/
    Sphynx kittens for sale, sphynx kittens for sale $500

    回覆刪除