Conditional command line arguments in Python using argparse

前端 未结 4 1500
失恋的感觉
失恋的感觉 2020-12-13 18:16

I\'d like to have a program that takes a --action= flag, where the valid choices are dump and upload, with upload being t

4条回答
  •  被撕碎了的回忆
    2020-12-13 18:36

    It depends what you consider "doing all the logic yourself". You can still use argparse and add the dump option as follows with minimal effort without resorting to sub-commands:

    from argparse import ArgumentParser
    from sys import argv
    
    parser = ArgumentParser()
    action_choices = ['upload', 'dump']
    parser.add_argument('--action', choices=action_choices, default=action_choices[1])
    parser.add_argument('--dump-format', required=(action_choices[1] in argv))
    

    This way argparse won't care about the dump format if the dump action wasn't selected

提交回复
热议问题