我对 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()
这似乎应该很容易实现,但我迷失了如何检测所有参数是否为假而不循环参数并测试是否全部为假的逻辑。
更新
多个参数一起有效,这就是我没有走 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'