Fix Python – Python argparse: Make at least one argument required

Question

Asked By – Adam Matan

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?

Now we will see solution for issue: Python argparse: Make at least one argument required


Answer

if not (args.process or args.upload):
    parser.error('No action requested, add -process or -upload')

This question is answered By – phihag

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0