Search code examples
pythonargparse

Argparse with OR logic on arguments


I am coding an argument parser for my script:

import argparse

parser = argparse.ArgumentParser(description='My parser.')
parser.add_argument('path',
                    type=str)
parser.add_argument('-a', 
                    '--all',
                    action='store_true')
parser.add_argument('-t', 
                    '--type',
                    type=str)
parser.add_argument('-d', 
                    '--date',
                    type=str)

This is the logic I want to implement:

  • path: must be provided always.
  • --all: if it is provided, the --type and --date should not appear.
  • --type and --date: must be provided only if the --all flag is not introduced.

The command would look something like this:

python myscript.py mypath [-a] OR [-t mytype -d mydate] 

How can I implement this logic?


Solution

  • You can do something like this:

    from argparse import ArgumentParser
    
    parser = ArgumentParser(description='My parser.')
    
    parser.add_argument('path',
                        type=str)
    parser.add_argument('-a', 
                        '--all',
                        action='store_true')
    parser.add_argument('-t', 
                        '--type',
                        type=str)
    parser.add_argument('-d', 
                        '--date',
                        type=str)
    
    args = parser.parse_args()
    
    if args.all:
        print('all argument flow')
    else: 
        if not args.type or not args.date:
            print('you need to put either all or specify both type and date')
        else:
            print(args.type, args.date)
    
    print('and',args.path)