私はPythonにかなり慣れていないので、コマンドライン引数を使用するときに簡単なスクリプトを構築する方法にこだわっています.
スクリプトの目的は、画像の並べ替えと操作に関連する私の仕事のいくつかの日常的なタスクを自動化することです。
引数を指定して、関連する関数を呼び出すようにできますが、引数が指定されていない場合のデフォルトのアクションも設定したいと考えています。
これが私の現在の構造です。
parser = argparse.ArgumentParser()
parser.add_argument("-l", "--list", help="Create CSV of images", action="store_true")
parser.add_argument("-d", "--dimensions", help="Copy images with incorrect dimensions to new directory", action="store_true")
parser.add_argument("-i", "--interactive", help="Run script in interactive mode", action="store_true")
args = parser.parse_args()
if args.list:
func1()
if args.interactive:
func2()
if args.dimensions:
func3()
しかし、引数を指定しないと、何も呼び出されません。
Namespace(dimensions=False, interactive=False, list=False)
私が欲しいのは、引数が指定されていない場合のデフォルトの動作です
if args.list:
func1()
if args.interactive:
func2()
if args.dimensions:
func3()
if no args supplied:
func1()
func2()
func3()
これはかなり簡単に達成できるように思えますが、引数をループしてすべてが false かどうかをテストせずに、すべての引数が false であることを検出する方法のロジックに迷っています。
アップデート
複数の引数は一緒に有効です。そのため、elif ルートをたどりませんでした。
更新 2
@unutbuからの回答を考慮して更新されたコードは次のとおりです
すべてがifステートメントでラップされているため、理想的ではないようですが、短期的にはより良い解決策を見つけることができませんでした. @unutbu からの回答を喜んで受け入れます。提供されたその他の改善点をいただければ幸いです。
lists = analyseImages()
if lists:
statusTable(lists)
createCsvPartial = partial(createCsv, lists['file_list'])
controlInputParital = partial(controlInput, lists)
resizeImagePartial = partial(resizeImage, lists['resized'])
optimiseImagePartial = partial(optimiseImage, lists['size_issues'])
dimensionIssuesPartial = partial(dimensionIssues, lists['dim_issues'])
parser = argparse.ArgumentParser()
parser.add_argument(
"-l", "--list",
dest='funcs', action="append_const", const=createCsvPartial,
help="Create CSV of images",)
parser.add_argument(
"-c", "--convert",
dest='funcs', action="append_const", const=resizeImagePartial,
help="Convert images from 1500 x 2000px to 900 x 1200px ",)
parser.add_argument(
"-o", "--optimise",
dest='funcs', action="append_const", const=optimiseImagePartial,
help="Optimise filesize for 900 x 1200px images",)
parser.add_argument(
"-d", "--dimensions",
dest='funcs', action="append_const", const=dimensionIssuesPartial,
help="Copy images with incorrect dimensions to new directory",)
parser.add_argument(
"-i", "--interactive",
dest='funcs', action="append_const", const=controlInputParital,
help="Run script in interactive mode",)
args = parser.parse_args()
if not args.funcs:
args.funcs = [createCsvPartial, resizeImagePartial, optimiseImagePartial, dimensionIssuesPartial]
for func in args.funcs:
func()
else:
print 'No jpegs found'