命令行參數 getopt模塊

getopt中的函數:
  getopt.getopt(sys.argv[1:], shortoptslongopts=[])
  args指的是當前腳本接收的參數,它是一個列表,可以通過sys.argv獲得
  shortopts 是短參數
  longopts 是長參數
 如果不知道長參數, 短參數是什麼的話,看下面這個例子:
# test.py
import getopt
import sys

def usage():
  print("This is a help message")

def test1(req):
  print(req)

def a_test():
  print()

def start():
    try:
opts, args = getopt.getopt(sys.argv[1:], "-h-a-t:", ["help", "all_data", "test_func="])
except getopt.GetoptError as e:
print(e)

for o, a in opts:
    
if o in ("-h", "--help"):
usage()
     if o in ("-t", "--test_func"):
     test1(a)

     if o in ("-a", "--all_data"):
        a_test()
 
if __name__ == '__main__':
start()

# 1. 在終端執行命令的時候: 輸入python3 test.py -h 和輸入 python3 test.py --help 是一樣的效果 都會執行usage函數
# 2. -c: 是來獲取參數的 命令行輸入 python3 test.py -t hello 或者輸入 python3 test.py --test_func=hello

 

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