Variable Length Arguments

I am creating a python program using the argparse module, and I want to allow the program to accept either a single argument or 2 arguments.

What I mean? Well, I am creating a program for downloading / decoding MMS messages, and I want the user to be able to provide a phone number and transaction ID for MMS to download data or provide a file from their system of already downloaded MMS data.

I want something like this where you can either enter 2 arguments or 1 argument:

 ./mms.py (phone mmsid | file) 

NOTE: phone will be the phone number (for example, 15555555555 ), the mmsid line (MMS-Transaction-ID) and the file file on the user computer

Is this possible with argparse ? I was hoping I could use add_mutually_exclusive_group , but that doesn't seem like what I want.

 parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group(required=True) group.add_argument('phone', help='Phone number') group.add_argument('mmsid', help='MMS-Transaction-ID to download') group.add_argument('file', help='MMS binary file to read') 

This gives an error (removing required=True gives the same error):

ValueError: mutually exclusive arguments must be optional

Looks like he wants me to use --phone instead of phone :

 parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group(required=True) group.add_argument('--phone', help='Phone number') group.add_argument('--mmsid', help='MMS-Transaction-ID to download') group.add_argument('--file', help='MMS binary file to read') 

When I run my program with no arguments, I see:

error: one of the arguments is required --phone --mmsid --file

This is closer to what I want, but can I do argparse do (--phone --msid) or (--file) ?

+6
source share
1 answer

This is a bit beyond what argparse can do, since the "type" of the first argument is not known in advance. I would do something like

 import argparse p = argparse.ArgumentParser() p.add_argument("file_or_phone", help="MMS File or phone number") p.add_argument ("mmsid", nargs="?", help="MMS-Transaction-ID") args = p.parse_args() 

To determine if args.file_or_phone will be used as a file name or phone number, you need to check if args.mmsid None .

+4
source

All Articles