命令行参数 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

 

posted @ 2019-08-27 11:04  Iron-Mam  阅读(189)  评论(1编辑  收藏  举报