我正在编写一个脚本,从Web下载文件,执行一些处理并将数据存储到mysql数据库中。
我使用argparse
来接受参数。本质上,脚本将执行以下四项操作中的一项:
1)从Web下载用户提供的文件名并执行处理/ db-insert。
2)根据昨天的日期下载当前最多的文件名。我有一个cron工作,每天晚上凌晨2点运行这部分。
3)与#2相同,但是需要另外一个文件。
4)处理当前文件夹中的用户定义文件,并将其保存到同一文件夹中的输出文件中。
脚本只能执行上述4件事中的一件。因此,我想我可以使用互斥的可选参数,如下所示:
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-f','--filename',action='store',nargs=1,help='Filename to download')
group.add_argument('-b','--bulkfile',action='store',nargs=2,help='Bulk filename to process and save')
group.add_argument('-l', '--load', action='store_true', help='Download current load data')
group.add_argument('-s', '--supply', action='store_true', help='Download current supply data')
args = parser.parse_args()
if args.filename:
do something
elif args.bulkfile:
do something
elif args.load:
do something
elif args.supply:
do something
else:
print "Improper usage. Can only use [-f | -b | -l| -s]"
return
我知道这不太理想。我宁愿让argparse
处理它的用法部分。我正在寻找实现目标的最佳方式。我很感激帮助。
答案 0 :(得分:2)
argparse
将为您处理使用情况。运行没有参数的脚本我收到此错误消息:
usage: test.py [-h] (-f FILENAME | -b BULKFILE BULKFILE | -l | -s)
test.py: error: one of the arguments -f/--filename -b/--bulkfile -l/--load -s/--supply is required
使用-l
和-s
同时运行
usage: test.py [-h] (-f FILENAME | -b BULKFILE BULKFILE | -l | -s)
test.py: error: argument -s/--supply: not allowed with argument -l/--load
解析器会自动为您提供互斥参数的错误消息。
答案 1 :(得分:1)
本着svn
或git
的精神,您可以使用sub-commands。