Skip to content
Advertisement

Python argparse: Make at least one argument required

I’ve been using argparse for a Python program that can -process, -upload or both:

parser = argparse.ArgumentParser(description='Log archiver arguments.')
parser.add_argument('-process', action='store_true')
parser.add_argument('-upload',  action='store_true')
args = parser.parse_args()

The program is meaningless without at least one parameter. How can I configure argparse to force at least one parameter to be chosen?

UPDATE:

Following the comments: What’s the Pythonic way to parametrize a program with at least one option?

Advertisement

Answer

if not (args.process or args.upload):
    parser.error('No action requested, add -process or -upload')
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement