The argsparse module can be used to parse command line arguments.
This article is written for argsparse with Python 3.
argparse reads the command line for you. You say what you expect and it
writes the parsing, the error messages and the help text.
Sure you could write your own parser to get command line arguments from sys.argv, but argparse makes it easier.
By default it will add a help option, even if you don’t specify it. Let’s show the sort of thing you can do with argsparse.
Arguments
The code below is a Python program that takes opitional arguments. We create an ArgumentParser instance and create new arguments by callig nt he method add_argument().
Then when the method parse_args() is called, it uses all that information and interprets sys.argv automatically!
import argparse |
If we save the code above as example.py, it can be run like this:
We have set the parameter required=False, they are optional.
open.txt
If we set the last parameter to required=True, it has to be specified or it will throw an error.
The two kinds of argument
- A positional argument has no name.
add_argument('filename')takes the first value. - An optional argument starts with a dash.
add_argument('-v', '--verbose', action='store_true')is a flag. type=intconverts the value for you.default=andrequired=Truecontrol what is optional.help='...'shows up in--help.parser.parse_args()does the work.
Call your parser from a function with if __name__ == '__main__': so the
file can be imported without argparse taking over the command line.
If you want to try this yourself, the exercises on PyChallenge turn the same idea into a few short problems with instant feedback.
