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

 

转载于:https://www.cnblogs.com/zhangxin-/p/11417047.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值