getopt中的函數:
getopt.getopt(sys.argv[1:], shortopts, longopts=[])
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