私は現在 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)
else: print(args.direct) は、目的の動作が得られるまでテストするためのものです。
私はPythonが初めてなので、他の観察/提案も大歓迎です。