Understanding Python: Argparse CLI

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] welcome back to understanding python my name is jake and today we'll be building upon what we learned in the previous video this time instead of manually parsing and validating cli input we'll be using python's built-in our parse module as we go if you learned something new let me know by liking the video now let's get started in our last video we made a pizza builder program with a command line interface which we see on the left hand side of the screen in here we did have to define a few helper functions for us to process the input as well as validate the input if you haven't watched that video i highly recommend you check it out there will be a link in the top right of the screen now however today we're not going to be manually validating input or processing input we're going to be using arg parse we also won't have to define custom help text like this instead we're going to let arc parse do all that work for us we will borrow a couple of things from this pizza builder so we don't have to do that same work again let's keep our definitions for sizes and crusts and pop them over here on the right which is what we'll be working in i also want to keep the output for build pizza to be approximately the same so we'll copy that helper function and just pop that down in there and that should be just about all we need from the old pizza builder so we'll just give ourselves a little bit more room and go back up to the top in order to use arc parse we are going to just simply import arc parse we'll leave all this alone for now and head down to the bottom or we'll write our usual if name is equal to main statement and this is where we'll start to define our rpar cli the first thing we're going to need is to instantiate a parser object for this we'll say parser is equal to argparse dot argument parser now we could be perfectly fine passing nothing into the argument parser class or it's init however if we want to have a description like we did with pizza builder where we said welcome to the pizza builder let's build a pizza what we can do is simply copy that and over here where we call argument parser we'll set its description equal to exactly that text this time let's be slightly more excited by putting an extra exclamation point now we have a parser object now there are a few things we can do with this parser object but when it comes to building a cli we're mainly going to be focusing on parser dot add argument the add argument method itself can take a number of arguments when you call it it has a combination of positional and keyword arguments first we're going to tell it that the name of this argument is size by simply passing in a positional argument with the string size we can specify the data type that we're expecting from the cli by saying type is equal to string meaning that anything passed in should be a string or can be converted into a string one of the great things about arc parts is all the features that are built into this add argument method one of these which you're going to be taking advantage of today is called choices with choices you can specify some kind of iterable which will make sure that the user only inputs values that are in that iterable for our iterable we're going to use the sizes constant and specifically the keys of that sizes constant so the choices are going to be s m l xl and xxl if the user inputs any value that is different from that then arc parse is going to spit out a warning and let them know that that isn't an invalid choice and give them a list of the valid choices final argument we're going to add is some custom help text and help text for size is size of your pizza awesome so let's save that and run it and see what happens okay we've ran it and nothing happened what happens if we're specified stretch help nothing how come this parser isn't working well there's one crucial thing that we need to do to actually make all of this work we need to tell it to actually parse the arguments so we'll store that as parsed args is equal to parser dot vars args notice that we're not passing anything in to parse args this is because by default parse args is going to parse sys.rgv just like we did in our previous video it will also ignore that first entry of the sys.rgb argument list so it's only going to parse the parts that are distinct from saying pizzabuilder.pie let's save this and try it again and we've printed something out let's give ourselves some more room and we see usage pizzabuilder.pie dash h or dash help and then we see the options that are available for size sml excel and xxl we also see our welcome message or description as well as the positional arguments here which again repeats the valid sizes as well as the help text size of your pizza we also see something really nice here where we get the dash h and dash dash help behavior for free you don't have to do anything for arc parts to include that for you now you can turn that off if you want to but for our usage we're just going to leave it as is okay so one argument down let's go ahead and add another this one is going to be the crust which is very similar to what we did for size so we'll copy and paste that change out size or crust rest and this will be trusts dot keys and the help text for this will be type of pizza crust okay we'll save that and see how it looks perfect so we now have a new positional argument the valid options are normal thin and deep we see type of pizza crust now in our original pizza builder you'll see that we have something similar we have arguments which were size and crust and we also had options now how do we add in these options to the optional arguments down here here's where we get into a little bit of specifics about those positional arguments we're passing into add argument i'll write out the positional argument for extra cheese and see if you can notice the difference do you see it the difference between these is that extra cheese as a dash dash in front of it you could also optionally add a dash c here one or both of these are valid for adding optional arguments to your parser so our parts will see these without the dash as positional arguments and these with a single or double dash as optional arguments this is very important to keep in mind as these first two arguments are implicitly required meaning that if the user doesn't pass in a value for those they're going to get a warning however for these unless you make them required by default bypassing in required equals true then a user doesn't have to pass in values for those arguments because they're optional for us we're going to take off the required equals true because i want people to make pizzas without having to pass in extra cheese and if you don't say required is equal to true is false by default now again remembering back to our previous video extra cheese is what i called a flag meaning if you pass in extra cheese we would say that that value is true otherwise the value is false we can get the same behavior for free with arc parts by specifying the action so there are a few different actions that are available with arc parse the one we're going to be using today is called store true meaning that if this argument is passed in or the dash c form it's going to store the value of true into extra cheese so this is how we get our flag behavior if someone runs it with extra cheese extra cheese will be set to true otherwise if they don't pass it in extra cheese will be set to false now if you're a big cheese lover and you want extra cheese to be the default you can reverse that behavior by specifying store false so if they don't pass in extra cheese then it's going to say extra cheese is equal to true if they do say extra cheese then it's going to say extra cheese is equal to false because it's storing the value of false into extra cheese when this flag is passed in now extra cheese might be a bit long for a variable name to work with the extra we don't really need to have that on there so we can take advantage of another feature of arc parse which is setting guest or destination is equal to cheese meaning that instead of storing extra cheese into a variable called extra underscore cheese it will store it into a variable called cheese and i'll show you where that variable lives in just a few minutes but for now let's add in some help text also do the same thing real quick for extra sauce and we'll change that to a dash s now while this is a few lines the line length is getting a little unruly so give me a minute to make the formatting a little prettier there we go that looks much better okay so let's test this out a little bit more i told you that it's going to store things like extra cheese extra sauce as well as size and crust to variables that we'd be able to access let's see how we're going to access those let's print out what exactly parsed args is and to illustrate the difference between specifying a destination we're going to comment out the destination for sauce let's save this first let's take a look at the help text make sure everything looks good good we solve our positional arguments and now we have the extra cheese and extra sauce optional arguments now let's actually pass in some values for this for our size we'll go with large and then the crust will say thin this time we're going to pass in dash c as well as dash s remember that we now have the shorter form of these as well we could just have easily have said dash dash extra sauce but for consistency we'll stay with dash s so you don't think that that is affecting the variable that's returned we'll run this and we see what was printed out is a namespace object and in this object we see it has attributes size is equal to the string l crust is equal to the string thin cheese is set to true and we see extra underscore sauce is equal to true perfect now if we were to revert this change so uncomment that give ourselves a little bit more room and run it again we now see instead of seeing extra sauce we just see sauce at this point you might be thinking that we're missing one crucial thing for our entire pizza builder and you're absolutely right we do not have a way to specify toppings so let's do that now parser dot add argument this one is going to be for consistency dash t as well as dash dash toppings you don't always have to give it that shorthand as a matter of fact i'm going to strip the shorthand from extra cheese and extra sauce because as a general rule if something is a flag in my clies i don't really like to have it as the short form some people do that's entirely personal preference but since toppings is not a flag we're going to offer the dash t option as well so let's also give it good formatting right out the bat the type of our toppings should be string and now we're going to do something really cool with our parse we're going to say that n arcs or the number of arguments is equal to a plus in quotes when we specify a plus for n args we're telling argparse that you expect at least one argument for toppings when passed in if you want to allow people to pass in zero or more you put a star both of these will be collected into a list of arguments passed into toppings which is going to be helpful for our processing later additionally if you wanted them to pass in specifically three toppings say this is a three topping pizza all the time then you can pass in the number three or five or any other integer you can think of like an 18 topping pizza finally if you want them to be able to pass in multiple arguments but only consume or only store one argument you can add the question mark there but we're going to keep it as a plus so number args is equal to plus or a list of one or more toppings finally let's add some help text there we go we'll save it and see how this looks with the help text perfect welcome to pizzabuilder we have our positional arguments we have our optional arguments including the free help we also have toppings in there let's run this through with our previous example and as expected since we passed in dash c and dash s which are no longer part of our extra cheese and extra sauce optional arguments it gives us a nice warning here it says error unrecognized arguments dash c and dash s this is the kind of input validation that it's doing automatically for us while we're testing bad cases let's go ahead and not specify a value for crust and we see the following arguments are required trust we get rid of that l there we see the following arguments are required size and crust okay let's put that back extra cheese okay we see our namespace object course size is large crust is thin toppings is none cheese is true and sauce is false now let's try adding some toppings see tea bacon and let's try saying onion as well we see we now have under toppings a list including bacon and onion if we just specify bacon it's still a list so if we pass in nothing for toppings we get none otherwise if something is passed in we're going to get a list perfect we're now ready to plug this into our build pizza helper method okay our build piece is still going to accept an order this time instead of order being a dictionary it's going to be a namespace object meaning instead of saying order and then the key of size we can just put order dot size same thing for crust dot crust again since it's a namespace object and we know that if toppings aren't specified it's going to be none we can just have order dot toppings so if order dot toppings we know that order dot toppings would be a list because it is a truthy value or it's a list with some entries in it otherwise we're not going to add toppings to our pizza same thing with extra cheese this time instead of being extra cheese we can just say cheese because remember that we are storing this with a different destination destination being cheese which we also see down here in the namespace object so if order.cheese we're going to add in the extra cheese same thing with sauce beautiful it even looks better this way as well the last thing that we need to do is store the output of that as pizza call build pizza pass in our parsed arguments and finally print out the same message that we did in the previous video your pizza is pizza for now let's keep this little print statement in here just so we can see how everything is running clear our output and see how our previous order would look okay it says your pizza is large thin crust with bacon plus extra cheese awesome let's add back in the onions and then we'll change it up from a thin to a normal pizza and this one is going to be xxl here we go your pizza is extra extra large with bacon onion plus extra cheese and we see that this matches up with the values that were stored in the namespace object so now that we've verified that the namespace object works perfectly fine we'll get rid of that print statement and see the final output here nice and clean if we were to pass in some bad values here so instead of having one of the accepted sizes we'll pass in q we see that the argument size received an invalid choice the choice that was invalid was q and it's telling the user to choose from small medium large etc as you would expect the same thing is true with the crusts instead of saying a normal crust we'll say a weird crust again involved choice weird and here are the options that are actually available for us we accomplished all of this in just 61 lines of code whereas our previous version took 88 lines of code and this is also with quite a bit of extra formatting that isn't technically needed and could likely reduce our lines of code by 10 or more well that wraps up this video now that you understand how to use arc parse to write clis try writing some of your own what is your favorite trick with arc parse or is it something i showed today leave a comment down below to let me know as always today's code will be added to the understanding github repo so check the description for a link and of course if you have any questions or suggestions or topics you'd like me to cover leave a comment for me to keep up with this series please consider subscribing thanks for [Music] watching [Music] you
Info
Channel: Jake Callahan
Views: 1,403
Rating: undefined out of 5
Keywords: python, python argparse, argparse, argparse python, python argparse tutorial, python tutorial, python command line arguments, argparse tutorial, python 3, python argument parser, python command line interface, python course, python for beginners, learn python, argparse in python, argparse python 2, python argparse module, python argparse example, what is argparse in python, cli, argparse in python example, how argparse work python, argparse python tutorial, understanding
Id: J51vxXAWigI
Channel Id: undefined
Length: 21min 11sec (1271 seconds)
Published: Fri May 14 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.