Script Tip: argparse (How to make your own CLI)
A huge part of any Python developer’s arsenal is the ability to link your Python program with “other stuff”. “other stuff” meaning everything from other programs to other humans to other developers. As your careers develop you learn how to write more something-Is. The most common ones will be:
- APIs - “Application Programming Interface”s (let programs talk to each other)
- GUIs - “Graphical User Interface”s (let humans talk to the program)
- CLIs - “Command Line Interface”s (let humans talk to the program but its easy to develop)
argparse works. The perfect tool for building a quick and easy interface with your Python script.
Introducing argparse
argparse is the builtin library to create CLIs with in Python. It is not the best, nor the simplest, but it is always there, and as such it is useful to know about this one because you may occasionally find yourself unable to install external packages for some reason and be forced to use it (this happens a lot commercially in my experience; usually for licensing reasons).
If you are open to 3rd parties then I suggest checking out the following options:
If this is a bit overwhelming Real Python has written a very nice article comparing all three AND argparse, which you should check out here.
This article, however, will focus on argparse and is aimed at people coming across it for the first time.
What does a CLI “look like”?
A CLI has the following components: “the command” (python in Python, or some other alias like py2 or py3 are common), “the option(s)” (flags that indicate what you want to do. The most common being the --help flag.), and “the argument(s)” (information you want to insert into the script, like the path to a file, for example). In vanilla Python there is one “command”, the call to python and at least one argument every time, the script name/path.
python and the argument is my_script.py.
sys.argv
OK but that’s all on the command line. How does Python access this information inside a script? Well, in Python, the builtin sys package has the property argv, which is a list of all the input arguments as strings. The delimiter separating the arguments is the space “ character, although substrings within the CLI command are preserved (strings contained within a pair of double quotes "...").
If you have a script (script.py) containing
Note: the double backslash is because I’m on Windows, which uses backslashes in paths, and backslash is also the escape character in Python strings, so it has to be escaped to be used in a path. As such, path visualisations in Python on Windows will be positively FULL of \\. Try to use pathlib where you can to get around this somewhat!
If we add more arguments to our command line we can see just how argv works.
Why is the backslash gone? Honestly, I’m not sure and I couldn’t find any info after a cursory google. If you have any idea why, please leave a comment! Although the reason is not important for this article because for the CLI the only argument we don’t care about is the first one because it is always the same!So,
argparse is essentially a package that parses sys.argv and makes sense of it, turning it into options and arguments for the CLI.
Note: All input on the command line are command line arguments but in the CLI, only some of those are CLI arguments. Some are what I’m calling options or flags.
Nitty-gritty of CLI
Generally CLIs make use of option-argument pairs. You provide some sort of option or flag and then the input corresponding to it, like--density 3.4 or --path .\\Program\\Python\\, and this makes sense. For example
--factorial and its corresponding argument is 9. Providing additional args throws an error, unless we were to modify the programn to handle it.
Scripts are not just limited to single pair either. We can write one to have multiple pairs as well:
Note: the--is a convention. Generally--is used before full words and a single-is used for the same argument but with a single character alias. This is most easily demonstrated with the example that--helpand-hare the same.
Constructing a CLI with argparse
OK so we’re ready to tackle the main topic of this tip now; apologies if you already knew all of the above. I like to cover all my bases in an article because one’s work may well be someone’s first exposure to any number of concepts, so it always pays to be thorough.
Anyway! How do we use argparse? It’s pretty simple, but requires a bit of mental gymnastics if you aren’t used to thinking about programming this way.
Your program executes in the following way:
- You smash that Enter button on the command line
- The arguments you added are all stored in
sys.argv - The program enters your script and starts executing things
sys.argv as I said before, and then your parser parses that.
So your program’s execution order should be structured like so
- Perform your imports (imports should always be at the top of the file in Python)
- Construct the parser
- Parse the args
- Perform logic based on the parsed args
- Other stuff
How do I construct the parser?
First of all you create an instance ofargparse.ArgumentParser.
--density which is a point of entry for the “argument” associated with it.
Now we parse the args, which stores all the supplied arguments in the returned namespace object that I always call args.
Note: If no arguments are provided toNow we haveparse_argsthen it will usesys.argv, but if you do provide a string it will actually parse that instead! It’s a neat little trick you can make use of when building argparse in non-standard locations like jupyter notebooks.
args we can get at all the inputs! For now let’s just print the density.
Note:OK so what happens if we run our program?argparsedoes some magic behind the scenes and strips away the--, so we don’t have to worry about that.
density the namespace with it is still created. In fact, we can use argparse to specify the default value should nothing be supplied. Which we would do by changing the add_argument line to
0.0 if nothing else is supplied.
And that’s pretty much it!
Some tips ‘n’ tricks about argparse
- You do not need to add an argument for
--help. This comes withargparse, and will always be present when creating a CLI with it. - When you add an argument in
argparseyou can specify thetypethat argument should be converted to, likefloatorint. If no type is provided the output type will always be a string unless it was not provided, which case the result will beNoneof theNoneType. - By specifying the
actionof an argument as"store_true"you can create an option that is parsed asTrueif it is present andFalseif it is not. If theactionis set to"store_false"instead the reverse is achieved!
- You can add an easy versioning return with the
"version"action, and the version to be printed can be specified with theversionkwarg. Like using the builtin--helpoption, the program will print the version and auto-quit afterward.
- When developing programs with
argparseit is best practice to group your code into functions, often in a separate file. Inscript7.pyI’ve grouped things as they commonly are.
argparse CLIs.
Closing Comments
This article should serve as a pretty good primer for getting started withargparse. I have also included all the scripts used here in my GitHub script tip repo, if you’re interested in playing around with them. That can be found here. Finally, I hope you enjoy making your own CLIs! The skill is ever a “tool for the box”.