小编d.l*_*ous的帖子

没有提供参数时,python argparse设置行为

我是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()
Run Code Online (Sandbox Code Playgroud)

但是,当我没有提供任何论据时,将不会被称为.

Namespace(dimensions=False, interactive=False, list=False)
Run Code Online (Sandbox Code Playgroud)

如果没有提供争论,我想要的是一些默认行为

if args.list:
        func1()
    if args.interactive:
        func2()
    if args.dimensions:
        func3()
    if no args supplied:
        func1()
        func2()
        func3()
Run Code Online (Sandbox Code Playgroud)

这似乎应该相当容易实现,但我失去了如何检测所有参数是错误的逻辑,而不通过参数循环并测试是否所有都是假的.

更新

多个参数一起有效,这就是为什么我没有沿着elif路线走下去.

更新2

这是我更新的代码,考虑到@unutbu的答案

它看起来并不理想,因为所有内容都包含在if语句中,但在短期内我找不到更好的解决方案.我很高兴接受来自@unutbu的答案,所提供的任何其他改进都将受到赞赏.

lists = analyseImages()
    if lists:
        statusTable(lists)

        createCsvPartial = …
Run Code Online (Sandbox Code Playgroud)

python python-2.7 argparse

7
推荐指数
2
解决办法
1万
查看次数

标签 统计

argparse ×1

python ×1

python-2.7 ×1