The Basics of argparse
In the previous lesson, I gave you an overview of the course. In this lesson, I’ll show you the basics of the
argparse is a powerful library for managing command line arguments to your Python programs. It’s part of the standard library, so there’s nothing extra to install. You do have to do a bit of work, though.
There are five basic steps. You need to import
argparse, create a parser, add arguments to the parser, and once you’ve got that all configured, you call the parser’s
.parse_args() method, which does exactly what it says. It parses the command line and returns to you a namespace object. That namespace object contains flags and data of what arguments were used.
The script in the top window here takes a couple of command line parameters and prints out a statement a number of times. To get at what was passed in on the command line, you need the
sys module. More specifically, you need the
argv part of the
sys module. Note that I’m using the second item in this list. The first item contains the name of the calling program.
As I mentioned before, everything off the command line is a string, unless you do something to change that, like I have here. Lines 8 and 9 use these two variables to print out Hal’s protesting statement to
name, and it does that
Right number of arguments, but the wrong type. Spelling out
Three is no good. It blows up the call on line 6. Again, you could write some code that checks this or handles it better, or you could use
argparse. It slices, it dices, it makes short work of tomatoes—oh, and it parses the command line too.
As the previous example had none, that’s not particularly hard to achieve. To get started, you have to import the
argparse library. Then you create a parser. Once you have a parser, you call
add_argument() to add an argument to the parser. In this case, I’ve called it
name, which is consistent with the previous program.
It will automatically convert it to such for me and handles the case if the user gives me something that can’t be converted. With my arguments defined, the last step is to invoke the parser using the
.parse_args() method. Notice you don’t have to do anything with
It does all that under the covers. Finally, lines 10 and 11 are essentially the same as before. The only difference is instead of using
num as variables, I am accessing them from inside of the
args namespace returned from
.parse_args(). Fire up the command line.
Become a Member to join the conversation.