该argparse
库非常擅长可选参数解析:
import argparse
p = argparse.ArgumentParser(description="My great script")
p.add_argument("sourceDir", type=str, help="source directory")
p.add_argument("destDir", type=str, help="destination directory")
p.add_argument("--match", type=str, dest="match", help="search pattern")
args = p.parse_args()
print args.sourceDir, args.destDir, args.match
这样,args.match
如果None
没有提供它:
Davids-MacBook-Air:BarNone dgrtwo$ python mycode.py ~/a/ ~/b/
/Users/dgrtwo/a/ /Users/dgrtwo/b/ None
Davids-MacBook-Air:BarNone dgrtwo$ python mycode.py --match "pattern" ~/a/ ~/b/
/Users/dgrtwo/a/ /Users/dgrtwo/b/ pattern
它还可以判断是否存在正确数量的参数:
usage: mycode.py [-h] [--match MATCH] sourceDir destDir
mycode.py: error: too few arguments
并包含一条帮助信息:
Davids-MacBook-Air:BarNone dgrtwo$ python mycode.py -h
usage: mycode.py [-h] [--match MATCH] sourceDir destDir
My great script
positional arguments:
sourceDir source directory
destDir destination directory
optional arguments:
-h, --help show this help message and exit
--match MATCH search pattern