user1348067
user1348067

Reputation: 35

How to structure optional arguments in python

I'm pretty new to python and im wondering whats the best way is to stucture and build my code in a specific data validation case. I'm building cmd line script that takes 3 arguments and save them to variables. The third argument is optional. How should i handle the optional argument. I get promted for "IndexError: list index out of range" when im not specifing the third argument.

Whats the most simple and practical why to validate user input with a optional argument?

user_cat = sys.argv[1]
user_id = sys.argv[2]
user_guid = sys.argv[3]

def validate(user_cat, argv_cat_list, user_guid):
    if len(user_cat) > 10 or user_cat not in argv_cat_list:
        print("Error! Please specify a valid category (AddDevice, GetAccount, c, p, GetDevices, r ,s)")
        sys.exit()
    elif len(user_id) == 36 or user_id.startswith("SAM-") and len(user_guid) == False:
        getInfo()
        sys.exit()
    elif len(user_cat) >= 10 and len(user_guid) == 36 and user_id.startswith("FRA-"):
        print ("Test-hest!")
    else:
        print("Error! Please specify a valid input")
        sys.exit()

Upvotes: 0

Views: 290

Answers (2)

vidstige
vidstige

Reputation: 13085

You should use argparse for this. You don't always need flags, sometimes just a positional argument is better as it saves typing, compare e.g. with cat. Try the following example

parser = argparse.ArgumentParser(description='LOLCATZ')
parser.add_argument('cat')
parser.add_argument('id')
parser.add_argument('guid')
parser.add_argument('optional1', nargs='?')  # positional and optional
parser.add_argument('--optional2')  # optional flag
args = parser.parse_args()
print(args)

Upvotes: 1

Winston Yang
Winston Yang

Reputation: 66

I would recommend the argparse library. Tutorial here.

Write something like:

parser = argparse.ArgumentParser(description = "[insert some description here]")
parser.add_argument('-i', "--user_cat", help = '[insert some help]')
parser.add_argument('-i', "--cat_list", help = '[insert more help]')
parser.add_argument('-u', "--user_guid", nargs = '?', help = '[insert some help]')
args = parser.parse_arg()
# Access the variables with args.user_cat, args.cat_list, etc.

Upvotes: 1

Related Questions