Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Help and Positional vs Optional Arguments

00:00 In this lesson, I’ll show you how to add some help text to your script and introduce positional and optional arguments.

00:09 The more arguments your program takes, the more confusing it can get. Go Google all the valid arguments for the ls command on Unix. Confusing is an understatement. Thankfully, argparse provides a mechanism for writing help.

00:23 All you need to do is add some extra parameters to your ArgumentParser object, and you’re good to go. Let’s go take a look at one.

00:33 Inspired by the Matrix movie—there was only one, I’ll fight you—this program prints out columns of random characters so that I feel cooler when programming wearing sunglasses. On line 4, I’m using the string library to string together—see what I did there?—a bunch of characters.

00:53 The string library defines some constants that are a subset of the ASCII table. Here, I’m creating a single string comprised of all of the upper and lowercase letters, the numbers, and some common punctuation.

01:05 The ArgumentParser class can be configured to change the behavior of the parser. Here, I’m going to show you some parameters that affect the help message. This first parameter I’m passing in is prog.

01:17 You use this to change the name of the program in the help message. Without this, the name will be the full matrix.py. Set the way I have, it will be just matrix.

01:30 Recall the previous lesson where I was arguing with Hal. If I didn’t put in the right command line arguments, I got a usage statement. On line 8, I’m overriding the default one, inserting an appropriate Keanu-ism into the beginning of the string. Note the use of the %(prog) variable indicator.

01:50 argparse will replace this with the name of the program, which of course I just overrode on line 7.

01:57 Line 9 gives the user more information about what the program does. This will appear after the usage statement in the whole help description.

02:08 And line 10 allows you to write some more text that appears after the whole help. I’ll just scroll down here.

02:16 The rest of this is the same kind of thing you’ve seen before. I’ve defined an integer argument, and then I call .parse_args(). Lines 16 through 18 do the work of printing the columns.

02:28 If you haven’t seen random.choice() before, it randomly chooses a single item out of an interval. In this case, it will be one character out of the TEXT string variable.

02:38 I’m doing that twenty times in a list comprehension in order to get twenty columns of output. On line 18, I print the columns by joining the content together, putting some space in between. All of this will be done args.num times. Taking the blue pill, or is it the red one?

02:58 I can never remember.

03:03 And there you go. Random screen characters. Of course, all that work was done to make the help prettier. So let’s go look at the help.

03:14 The command, without arguments, shows the modified usage line and both the usage line and the following line use the modified name of the program.

03:23 Well, what about the other stuff? For free, argparse gives you extra info through the use of the -h argument.

03:35 This shows the same usage statement, then the description. It then goes through each of the arguments—there’s only one of them this time—as well as showing you other options that can be used.

03:46 The only option available is the automatically created -h. At the bottom of the help text is the content from the epilogue. Told you it was pretty. Not Keanu-pretty, but pretty enough.

04:02 I kind of glossed over this in the previous example. argparse handles both positional and optional arguments. The number of rows in the matrix script was a positional argument. In fact, because I didn’t say otherwise, it was a required positional argument.

04:18 If I passed anything on the command line besides a single number, I would get an error. Well, that’s actually overstating it. There is one other thing I can pass. That’s the -h flag.

04:29 This is known as an optional argument and indicated by flags. In most Unix programs, it is common to support both single (-) and double (--) dash flags, where the double dash is a human readable word, and the single dash is a short form, typically a single letter. -h isn’t your only choice of an option.

04:49 You can define your own flags. Let’s go do that. You’ll find it doesn’t amount to a hill of beans. Wait for it. That’ll make sense in a second. Or of course, if you’re not into the silver screen, that beans thing is going to seem rather abstract. Anyhow, the casablanca script shows off the use of optional flags.

05:10 I’ve written a little Mad Libs program here, filling in one of the world’s most famous movie quotes with whatever you provide on the command line. The first optional flag is the --place flag.

05:22 Notice how you tell argparse that this is a flag instead of a positional argument. You name the argument with either a single or double dash in front of it.

05:30 I’ve done both here, which means the user can specify either -p or --place as their argument, because I haven’t specified otherwise, this flag expects an argument to go with it. In this case, it’s going to store whatever the user gave to the first flag inside of the args.place namespace item.

05:52 I then do something similar to define the --city flag. Here, I’ve also added a default value. If the user doesn’t provide a --city flag, args.city will contain the string "towns".

06:04 Line 8 is like line 6, but for a verb. And line 9 is a little different. It uses the action parameter to change what happens when this argument is used. Passing store_true to action tells argparse to change its behavior in a couple of ways. First, what gets stored in -r is a Boolean. Second, it does not expect a parameter to go with the flag. This flag is a pure flag.

06:31 It is either there or not. Like in line 7, I provided a default value here. Also, in this case, there’s no double-dash version. Having both kinds of flags is good practice, but argparse lets you do whatever you want. Scrolling down …

06:49 Lines 13 and 14 are where I print out the results. I do this by accessing the optional flags the same way I accessed the positional ones. If you have both a single- and a double-dash argument, argparse will store it using the long-form name and, in either case, without the dash or dashes. You can control this, but I’ll show you how to do that later. On line 16, I check for the -r flag, which in this case is short for Rick.

07:17 If the Rick flag is on, then Rick spits out his catchphrase after the Mad Lib. Yes, I know these are from completely opposite ends of the movie. Never mind that.

07:28 All right, here we go.

07:37 And there it is, using a mix of -p, -v, and -r flags. As -c wasn’t given, the default was used. Since these are flags, argparse doesn’t care about the order.

08:00 Order is all mixed up, but it still works. Unless otherwise indicated, flags are optional. There’ll be more on that later, too.

08:13 Unlike with required positional arguments, the program doesn’t spit out an error message. The default value for any argument in argparse is None unless you specify otherwise. You specify otherwise by using the default parameter, like I did with towns and False for the -c and -r flags. Without the flags, I end up with Of all the None in all the towns in all the world, she None into mine. It’s a very Pythonesque Mad Lib. Let’s look at the help.

08:48 That time, instead of using -h, I used --help, the long form. And argparse shows all the possible flags. It indicates which takes a parameter, shows you the names of the parameter and the flag. Later, I’ll show you how to make this prettier. Maybe not Bogart-pretty but prettier nonetheless.

09:11 I showed you the store_true action in this lesson. There are actually several others, as well, that allow you to control the arguments. Actions shout louder than words. Again with the oblique foreshadowing!

Avatar image for Carlo Barrientos

Carlo Barrientos on June 4, 2024

Try this (for fun):

$ python3 casablanca.py -p “Zoom meetings” -c internet -v logs -r

Become a Member to join the conversation.