- The above approach requires the arguments order to be "user",
"fruit". However, you must have seen some commands which allow you to
supply information
flexibly by command-line options:
- a.py -u Alice -f Apple
- a.py -f Apple -u Alice
- The argparse
module provides convenient tools for this:
#!/usr/bin/python3
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--user', '-u', action='store',
dest='user', default='alice')
parser.add_argument('--fruit', '-f', action='store',
default='apple') # if you omit "dest", it will use the
# option name ("fruit")
# Parse arguments
args = parser.parse_args()
print(args.user, 'buys', args.fruit)
- The argument can be any string.
If you want to limit the choices, try
parser.add_argument('-f', '--fruit', action='store',
choices=('apple', 'banana'),
default='apple')
- If you want a boolean flag, try
parser.add_argument('--line-number', '-n',
action='store_true',
default=False)
- You can retrieve the value with "args.line_number".
(Dashes are converted to underlines.)
- It is also possible to use argparse for position arguments without
flags. It can guarantee the number of arguments, and the valid choices
of an argument.
#!/usr/bin/python3
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('user')
parser.add_argument('fruit', choices=('apple', 'banana'))
# Parse arguments
args = parser.parse_args()
print(args.user, 'buys', args.fruit)
- Exercises: Enhance your "grep.py" to add an option
"--line-number", "-n", which will
prefix each line of output with the 1-based line number within
its input file.