为了演示方便,写了个小demo
import sys
def filter_exclude(*arglist,exclude=None):
results=[]
if exclude is None:
return arglist
else:
for i in arglist:
if exclude not in i:
results.append(i)
return results
def filter_include(*arglist,include='all'):
results=[]
if include=='all':
return arglist
for i in arglist:
if include in i:
results.append(i)
return results
def run(include='all',exclude=None):
list1 = ['beijing', 'shanghai', 'shenzhen','shenzhen longhua']
res = filter_include(*list1, include=include)
print(res)
res2 = filter_exclude(*res, exclude=exclude)
print(res2)
if __name__=='__main__':
run()
1.命令行参数,要写一大堆东西,判断用户提供了多少个参数
if __name__=='__main__':
if len(sys.argv)==3:
run(sys.argv[1],sys.argv[2])
if len(sys.argv)==2:
run(sys.argv[1])
if len(sys.argv) ==1:
run()
#调用:fire_demo.py shenzhen longhua
2.argparse模块,更加灵活,python内置库,不需要安装
import argparse
parse=argparse.ArgumentParser()
parse.add_argument("-i","--include",help='包含的',default='all')
parse.add_argument("-e", "--exclude", help='排除的')
args=parse.parse_args()
run(args.include,args.exclude)
#调用:fire_demo.py shenzhen longhua
# fire_demo.py -i shenzhen --exclude longhua
3.fire模块只需要一行代码,只需要一行,轻松搞定,谷歌出品,需要安装
import fire
fire.Fire(run)
# 调用:fire_demo.py shenzhen longhua
#fire_demo.py include shenzhen
# fire_demo.py run include shenzhen
#fire_demo.py - -include shenzhen - -exclude longhua
4.其他命令行解析模块,如click,getopt,大家可以自行研究,不过个人觉得有fire模块,完全就够用了,而且很强大
网友评论