Argparse教程
Argparse教程
概念
$ ls
不带参数独立运行命令
$ ls pypy
携带'pypy'被称为位置参数
$ ls -l
携带'-l'被称为可选参数
$ ls --help
'--help' 查看帮助文档
...
基础
import argparse
parser = argparse.ArgumentParser()
parser.parse_args()
$ python3 prog.py
$ python3 prog.py --help
usage: prog.py [-h] //未添加任何参数,默认含help选项
optional arguments:
-h, --help show this help message and exit
$ python3 prog.py --verbose
usage: prog.py [-h]
prog.py: error: unrecognized arguments: --verbose
$ python3 prog.py foo
usage: prog.py [-h]
prog.py: error: unrecognized arguments: foo
位置参数介绍
//echo.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo", help="echo the string you use here") //help帮助信息
print(args.echo)
//prog.py
import argparse
parser.add_argument("square", help="display a square of a given number", type=int) //type指定类型
args = parser.parse_args()
print(args.square**2)
可选参数介绍
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbosity", help="increase output verbosity", action="store_true")
//添加'store_true'默认为true
args = parser.parse_args()
if args.verbosity: //参数没有指定,变量值为None
print("verbosity turned on")
结合位置参数和可选参数
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="display the square of a given number")
parser.add_argument("-v", "--verbosity", action="count",
help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
print("the square of {} equals {}".format(args.square, answer))
elif args.verbosity == 1:
print("{}^2 == {}".format(args.square, answer))
else:
print(answer)
https://10.0.0.65:888/cgi/maincgi.cgi?Url=HostObj&Act=Add"
Cookie:
POST
def_host_name= &def_host_ipad= &def_host_ipad= &def_host_ipad=