0

I'd like to check if action='store_true dependent script arguments were provided. For example,

run.py --save_files --out_dir "saved_files" --files_to_save 10

Such that whenever run.py --save_files is called without --out_dir or --files_to_save, it fails and shows an error message.

I am trying to do it the following way:

class CheckedStoreTrue(argparse._StoreTrueAction):
    def __call__(self, parser, namespace, values, option_string=None):
        if not namespace.out_dir:
            parser.error("Please provide an output dir!")
        if not namespace.files_to_save:
            parser.error("Please provide a number of files to save!")
        setattr(namespace, self.dest, values)

then in

prs.add_argument(
    "--save_files",
    action=CheckedStoreTrue,
    required=False,
    help="Save files.",
)

This does not work and keeps throwing Please provide an output dir! even after I provide the out_dir parameter. If I check the namespace content, I see out_dir=None. I wonder why?

minerals
  • 6,090
  • 17
  • 62
  • 107
  • 1
    Why create an action? Why not just check the condition after parsing the arguments? Just like here: https://stackoverflow.com/questions/27411268/arguments-that-are-dependent-on-other-arguments-with-argparse – Tomerikoo Aug 19 '20 at 15:34
  • A subcommand would probably be more suitable: `run.py save_files --out_dir "saved_files" --files_to_save 10`, with the options being marked as required (though I would then prefer a simple pair of positional arguments instead of options). – chepner Aug 19 '20 at 15:36
  • slap! stupid me – minerals Aug 19 '20 at 15:37
  • 2
    Arguments are processed in the order given in `sys.argv`. `--save_files` is first, so your `CheckedStoreTrue` runs before any `out_dir` values (other than default) have been put in the `namespace`. It might run as intended if put last. Interdependencies that depend on the order of arguments are best implemented after parsing, as opposed to during. – hpaulj Aug 19 '20 at 15:41

0 Answers0