A Simple CLI Prototype
00:00 In this lesson, I’ll take you through a really simple command line interface prototype. That’s kind of what you might call a naive implementation because it only uses Python list comprehensions and conditional logic to do its parsing, and it doesn’t include any kind of type validation.
It then transforms the arguments and prints them out according to the following rule.
-c option means that all of the arguments printed out will be capitalized, whereas the
-u option makes them uppercase, and the
-l option makes them lowercase.
00:42 Now, this naive script separates the options and the arguments in the following way. It uses list comprehensions to filter the options as any argument passed in from the command line that starts with a hyphen.
So, this gets the options and the arguments apart quite easily. Then, the logic to decide what to do based on which option was included can be simply if the
"-c" option is in options then print out the space-joined version of
[arg.capitalize() for arg in args].
So, just print out all the
args and make them capitalized. The other two will work in exactly the same way. So if
"-u" is in the
opts, then you print out the uppercase version of all the
args, and if
"-l" is in the
opts, you print out the lowercase version of all of the
but I should have just written
.lower(). That happens sometimes. It prints out
A FEW ARGUMENTS in the uppercase version, and then I can do lowercase and I can say
A Few ARGUMENTS, and it will print them out all in lowercase. So, it works just fine. That’s good to hear. Now, you’re probably already noticing that this has a lot of limitations. First off, this separation strategy, which separates options and arguments based on purely a list comprehension, isn’t great because, A, it doesn’t enforce an ordering—so,
# Enforces no ordering—so you can put in these options and arguments in any order that you want.
So, this isn’t great because it’s not very flexible. There’s not really much you can do with this, aside from just have simple options that will apply to every argument. And then, of course, this logic, here, actually makes the behavior of the final product a little bit unpredictable. So for example, if I say
python cul.py and then I pass in the lowercase option and then I say
A Few ARGUMENTS, but then I pass in the uppercase option, it’s actually the uppercase option that prevails.
03:26 So, even though this simple script really works well for its purpose, it has some interesting edge cases in behavior that you wouldn’t quite expect, because it doesn’t have a sophisticated enough parsing strategy. In the next lesson, I’ll show you how you can use regular expressions to get a little bit more in-depth with parsing and enforcing some of these things that this script doesn’t actually do.
Become a Member to join the conversation.