0

I use the following code to parse argument to my script (simplified version):

import argparse

ap = argparse.ArgumentParser()
    ap.add_argument("-l", "--library", required=True)
ap.add_argument("--csv2fasta", required=False)

args = vars(ap.parse_args())

For every way the script can be run, the -l/--library flag should be required (required=True), but is there a way that it can use the setting required=False when you only use the --csv2fasta flag?

justinian482
  • 845
  • 2
  • 10
  • 18
  • 1
    Not an exact duplicate, but related: https://stackoverflow.com/q/19414060/2422776 – Mureinik Jun 26 '21 at 20:21
  • Sometimes it's simpler to give the "conditionally-required" argument a reasonable `default`, and not worry whether it's been provided or not. Think about what's simplest (and least error-prone) for your users. – hpaulj Jun 26 '21 at 21:10

1 Answers1

1

You have to write your test after parsing arguments, here's what I do for such cases:

def parse_args():
    ap = argparse.ArgumentParser()
    ap.add_argument("-l", "--library")
    ap.add_argument("--csv2fasta")
    args = ap.parse_args()
    if not args.library and not args.csv2fasta:
        ap.error("--library is required unless you provide --csv2fasta argument")
    return args
$ python3 test-args.py
usage: test-args.py [-h] [-l LIBRARY] [--csv2fasta CSV2FASTA]
test-args.py: error: --library is required unless you provide --csv2fasta argument

$ python3 test-args.py --csv2fasta value
Balaïtous
  • 826
  • 6
  • 9