Andy
Andy

Reputation: 51

Python - Optional Command Line Argument

I would like to have an option -n, that will allow users to specify a size of a list. The default will be 30. So:

./findNumberOfPlayers.py -n10

I haven't done any command line arguments with python before but am confused with how to include -n10 within the program. I understand I would import sys and have 12 assigned to sys.argv[1] but how does it work with -n10?

Thank You! I appreciate the help.

Upvotes: 1

Views: 1009

Answers (1)

ComputerFellow
ComputerFellow

Reputation: 12108

Use argparse.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-n", "--number", help="Enter a number", type=int)

You can then access the arg like this -

args = parser.parse_args()
num_players = args.number if args.number else 30

Upvotes: 2

Related Questions