我目前正在研究argparse模块,我想我的计划,以这样的表现:使用argparse参数以不同的方式
$ python cldir.py # this should delete all .meta files in ~/downloads
$ python cldir.py -d /path/name/ # delete all .meta files in /path/name
$ python cldir.py -d /path/name -e txt # should delete all .txt files in /path/name
现在,我知道我需要使用的文件扩展名的另一个理由( - e在这种情况下),但我想知道我可以如何使-d开关行为如上所示。
这里是我到目前为止的代码:
#!/usr/bin/env python
import argparse
import os
import glob
version = "0.1.1"
parser = argparse.ArgumentParser(
description = 'cldir: clear a directory from .meta and other unwanted files')
# arguments list
parser.add_argument('-v', '--version', action='version', version = version)
parser.add_argument('-d', '--direct', action = 'store_true')
args = parser.parse_args()
if args.direct == False:
path = os.environ['HOME'] + '/downloads/'
files = glob.glob(path + '*.meta')
if len(files) == 0:
print('No .meta files found in ~/downloads')
else:
for f in files:
os.remove(f)
print('%d file(s) deleted' %len(files))
else:
print(args.direct)
的东西:打印(args.direct)只是用于测试,直到我达到所期望的行为。
任何其他观察/建议也非常受欢迎,因为我是新来的蟒蛇。
是的,默认=元将做一些修改我猜测的树,谢谢! :) – yaku