python:argparse实现帮助文档,参数传递
2020-12-09 本文已影响0人
胡童远
导读
argparse模块实现写帮助文档和命令行传递参数,甚至设置脚本使用密码,初学很多参数还没用过。
一、一个实现加法的脚本
-p 密码项,if判断执行条件,必填
-a 参数1,整型,设置默认
-b 参数2,整型,设置默认
cat test.py
#!/usr/bin/env python3
import re, sys, os, argparse
parser = argparse.ArgumentParser(usage="This is a help document: ", description="python3 script.py -a [num2] -b [num1] -p [password]")
parser.add_argument('-p', required=True, help='remember your password')
parser.add_argument('-a', default=100, type=int, help="the first number a")
parser.add_argument('-b', default=200, type=int, help="the second number b")
args = parser.parse_args()
if args.p == "huty":
print("Right password, welcome!")
print("a = %d and b = %d"%(args.a, args.b))
print("a + b = %d"%(args.a + args.b))
else:
print("Wrong password, try again!")
二、查看帮助
python3 test.py -h
python3 test.py --help
莫名出现大写字母,未解决
三、读取命令行参数
python3 test.py -a 10 -b 20 -p huty
四、使用默认参数
python3 test.py -p huty