Argparse Tutorial - Python 2023 (Creating Your First CLI)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video we're going to be covering how you can create a command line interface with ag pass in Python and we're just going to be covering the basics so you can get started and later on on this channel I will be showing you how to create more complex programs of course but to get started it's important we grasp the basics so a good example of a command line interface would be pip itself as you can see here we can type in PIP and we can give it some sort of command or some sort of flag so right now we're just asking for help and it's going to give us all this information the commands we can use with it the usage and of course the options that we can provide with it so I'm going to be showing you the basics of how you can get started with creating this kind of command line interface so the first thing we have to do is import from ARG pass the argument parser and the namespace and here we're going to create our very first basic command line interface so the first thing we have to do is create a parser and this is going to be an argument parser that we have to instantiate now with this part so we can start adding some arguments so that the user can interact with our script so he will type in parser dot add arguments and the argument we're going to create is going to be called Echo and we're going to provide some help so the user will know what it does and this is going to be Echoes the given string Now by adding an argument we are creating a namespace for that argument so now we have a variable called Echo as soon as we run our command line but once we have that argument it's also important that we have a way of retrieving it so to do this we're going to create some arguments and I'm just going to use the namespace type just to make it a bit more explicit that we're creating a namespace there and we're going to type in parsa dot pass args now it's not necessary that you include this this is something I do for my own specific reasons I like using types in certain situations and for me this just seems a bit more explicit than just providing args because now I know this is a namespace variable but what it does essentially is take the arguments we've created here and make them usable for us later down here so for example we can print args.echo as you can see we haven't really defined the variable Echo anywhere in our script and usually that would give us a name error but in this situation we have this special line of code here that created a namespace for this Echo variable so that we could use it later now if we run this program it's not going to work because this is usually not how you run a command line interface usually you would want to open up the terminal and I'm going to clear all of this so clear and inside here you would do something more like python main.pi because that is the file I'm currently in followed by the argument so here we can say hello and if we type that it's going to Echo hello it's going to retrieve this variable and it's going to put it in the namespace so that we can use it later and that was our first command line interface and that was a very simple example so let's continue with making this a bit more complex now let's say we want to make this program a bit more interesting we want to get a number and we want to square it for the user we're going to change this to square and we're going to change this to squares a given number and we're also going to specify a type for it we're going to say that this should be an integer or it shouldn't be accepted now the rest can stay the same except with the print statement we're going to type in args dot Square because we've changed this to square now and we want to square that number now if we run the script again you'll see that if we try to run it with hello it's going to say that we have an invalid int value to make this actually work we need to type in Python main.pi followed by the number that we want to square that's the argument that we want to provide so that will give us 100 back as a result so far so good we have a very simple command line interface that allows the user to square the number but let's make it a bit more advanced by adding some positional arguments and positional arguments are optional so it's going to give the user some extra options with the code that we're providing in case they want to use those options for example we're going to type in parsa dot add arguments and here we're going to type in the optional argument and we're going to add a short version and a long version and for the longer version you want to use two dashes and that's what defines it to be positional so here we're going to type in verbose and the help here is going to be provides a verbose description and we're also going to provide an action so here we'll type in action and we're going to store true so now if we add this to the command in the command line it's going to store the Boolean of true which means we can use that as a flag if we don't use this it's going to remain false but if we do we're going to be able to use it as a true value and let me show you right away how we can use it so now we have the arguments as always but here we can check if args dot verbose then we can do the following print and I'm going to paste in this string that just gives a verbose description of the operation that we are performing else we're just going to do what we already did and that is square the number normally so let's test this program out now we have python main dot Pi 10 if we run that it's still going to square 10 for us which is going to be 100 but we can actually now make it verbose we can type in dash V and it's going to say 10 squared is 100 and I also want to specify that the argument order does not matter you can do verbose first and then you can square something the order just does not matter and finally we can type in maybe let's Square two for example and let's add verbose with the Double Dash approach and it's going to give us the same result so you can decide to use the short version or you can decide to use the long version that's exactly what we defined up here and once again if you don't provide any of the positional arguments the program will still run fine because this is positional unless you want the user to Define it and in that case you would have to type in required and set it to true now instead of storing a value such as true we can also provide some choices I mean we can retrieve a value just as we did with square and use those values to make our program act accordingly so instead of action I'm going to change the program just slightly and I'm going to make sure that the input value is a is of type integer and I'm going to provide some choices so here the choices for the user will be 0 1 and 2. so these are the only choices that the user should be using with this positional argument now because this code is actually really straightforward I'm just going to paste it in and explain it so what I just pasted in is a simple check that looks for the value that we've inserted with verbose and it acts accordingly so if we add a 0 to verbose it's going to print option one otherwise it's going to print option two and finally it might print option three depending on these options so let's run the program and see how it works with the new choices that we've added so here we have python main we have two and we're going to try to run it without any choices so we're just going to put Dash V and it's not going to allow us to do that because it expects one argument but now if we do it with an argument we can say zero for example and it's going to pick option one for us so we were able to add some extra input to our program to make it act a bit different and if we do this with a number that's not in the choice list right here that says 0 1 2 you'll see that it's not going to run because it's going to say error argument verbose invalid choice for and it will help us with choosing from 0 1 and 2. now at any point in the command line you can always do Dash H for help and you'll see the variables that you've provided along with the descriptions that you've provided for them so in general it's a good idea to provide a descriptive help message otherwise the users might be a bit lost now there's actually one more thing I'm going to show you before we move on to creating our very first basic command line interface and to do this we're going to remove this section over here and modify the code as follows so the next thing I wanted to show you is that we can actually add a default value to our arguments so if we don't insert anything it's not going to give us that error that we're missing an argument because now we have a default argument that is inserted automatically and also for the positional arguments I'm going to show you another cool feature that we can use with it because right now we only used 1V but what happens if we use two v's or three V's how can we actually turn that into a piece of functionality so to do this we're going to modify the help description a bit so we're going to call this verbose description and we're going to say use double v for extra verbose and we're going to provide a special action which is called count and what count does is count the occurrences of the V so that we can act upon it accordingly now as always we have our arguments here in this namespace and we want the result of type integer to equal args.square to the second power now here is where it becomes interesting we can type in if args dot verbose is equal to one then we will print the following verbose message so the result is result L if args dot verbose is equal to two we'll print the second verbose message which is even more descriptive than the previous one else we're just going to print the regular message so print result and actually for the default argument to work we do need to provide one more keyword argument and this is the n args so this is asking for how many arguments is it looking for the question mark denotes that it's only looking for one argument because sometimes you can pass in multiple arguments so this actually tells you how many it should look for so now since we're not passing in any arguments it's going to default it to zero because we're not passing in anything and to make that more obvious we're just going to type in Python main.pi and we're going to tap in enter so the value is going to be set to 0 as the default without this we're going to get an error because it's not going to know what values to look for but as you could see right now if we run the program and we don't insert anything it's going to give us 0 as a default but let's look at the more interesting aspect which is counting the occurrences of the verbose variable in this script so here we'll just type in Python main.pi we want to square the number of two and here we'll add AV so it's going to give us the verbose description of that calculation but if we add two of these we're going to get an even more verbose description of what we just created as you can see 2 to the power of 2 is 4 and we can add as many V's as we want and as you can see if it's not one or two it's going to default to the else statement so you can add as many if else conditions as you want depending on how verbose you want it to be and it's just cool because you can really change up your program in a cool way and this can also be called like this you can say Double Dash verbose Double Dash verbose and it will act the same way as adding the two double V's we've now covered a lot of the basic functionality that's required to use agpas so let's create our very first simple command line interface so to get started we need to create a passer as always and that's going to be an argument parser then let's add some parser arguments so here we'll type in Passa dot add argument and the first one is going to be a it's going to be of type integer and we're going to provide some help that helps the program that this is the base value and we're still going to square the numbers or we're going to create the functionality that allows the user to create a calculation based on two numbers the base number and the exponent and we're going to give the user the result in many different ways then we will duplicate this we'll say B which is of type int as well and we're going to call this exponent and finally let's add a positional argument so parser add argument and we're just going to add the verbose argument again so here we got verbose and the long version and we're going to have an action which is going to be set to count and finally we're going to give it a help message so the user will understand what it does so the message will say provides a verbose description use double V for extra verbose now just as from earlier we're going to create the namespace for these arguments and we're going to type in passer.pass args then we're going to get the results of type integer which is going to equal augs a to the power of args B for the fun of it I'm going to use match in this case so match args verbose and I know it's for pattern matching but sometimes it's fun to use it instead of if else so here we'll type in case one and we're going to print the formatted string of the result is result case two and this one is actually a really annoying to type so I'll just paste it in we're going to print that aux a to the power of augs B is equal to the result and every other case is going to be just printing the result and before we run this I also want to show you another cool thing you can do and that is adding a usage message so here you can type in Passa dot usage and you can add a string that defines how you should use this program so here we can type in use it like this and that message really sucks I really don't recommend you do something like that but now if we clear this and we run our program we say python main.pi and we type in dash h at the top you're going to have a usage message that says use it like this it's going to give you and then it will give you all of the useful information that you're used to seeing if you decide to exclude this it will give you a default one so let's go back and run this one more time and the default one is just going to look like this which is kinda hard to read but at the moment it's much more descriptive than what I just created so that's just a neat feature you should be aware of in case you want to make it more descriptive but let's see how we can actually run this so let's make some space and here we'll type in Python main.pi and we'll add two and five and if we run it we'll get 32 back now we can do 2 and 5 and we can also mention the verbose flag and it will give us the result is 32. we can even make it extra verbose all right let's do a double verbose and it will give us the double verbose option and that's going to be the first command line interface that we've created successfully but there's one more thing I'm going to show you in this lesson so that you can really get a good start with command line interfaces and that is how to deal with conflicting arguments because maybe you'll have an option that says verbose but you might also have an option that says silence so of course one of these options is going to do the exact opposite and I'm just going to paste it in like this so as you can see right here we have an argument that silences the program we provided the silence variable the action is going to store a flag and here it's going to help us generate a silent version of the output which is the exact opposite of the verbose option so if you display both of these it's usually an issue and if we actually specify both of these right now it's going to run because we didn't tell the program that both of these should not be put together so what we're going to do is go next to the parser up here and we're going to create a group and the group is going to be passer dot add mutually exclusive group so the way this works is that instead of typing passer we're now going to type in group because this is going to belong to a group and what this tells the program is that only one of these options should be run at one given moment so let's try to run this right now and if we type in main.pi and we do Dash H you'll see it's going to give us some more options but if we scroll up here we're now going to have the two options inside a list with a pipeline the noting that we can only pick one of them when we are running the program so let's go back to the bottom clear all of this if we type in now main.pi to 5 V and we also type in silence it's going to say silence is not allowed with argument Dash V verbose but now we can do something such as dash s and the program will work perfectly fine so in case you need to avoid two arguments being used together do create a exclusive group for them so that you can avoid silly mistakes such as that one and we're not really using that silence variable so if you did want to use it you would have to type in args dot silence so if ox.silence is true we're going to print silenced else we're going to do what we usually do and we're going to try to print the verbose option so now if we run this one more time you'll see that if we silence it it's going to say silenced it's not going to give us an output but if we add the verbose flag it's going to print the verbose version but anyways that's actually all I wanted to cover in today's lesson I know this was quite a lot to grasp I am going to leave a link to the documentation in the description box down below because I actually grabbed all of this from the python docs and changed it just slightly so that I could explain it a bit more easily so as always thanks for watching and I'll see you in the next video
Info
Channel: Indently
Views: 29,439
Rating: undefined out of 5
Keywords: pyton, pyhton, pythn
Id: aGy7U5ItLRk
Channel Id: undefined
Length: 18min 59sec (1139 seconds)
Published: Thu Jan 26 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.