For example, if I am writing a program to scrape a webpage a required argument could be the page’s domain.
Documentation: It is important to write out the function of each option and argument so that a new user can figure out how your program works.
Handle error cases: Let the user know exactly what went wrong and whereRuntime status: If the task does not complete instantly, you should print out the current progressReading arguments using argparseArgparse is a Python standard library module for parsing command-line arguments.
You as the programmer can define the arguments that are to be taken and argparse will figure out how to parse those out of sys.
argv (a list in Python, which contains the command-line arguments passed to the script, learn more here).
Argparse also automatically generates help and usage messages and outputs errors when users give the program invalid arguments.
It is very simple to use and makes it very easy to write intuitive CLI’s.
To get started, create a new file called test_cli.
py and import the module and initialize a new parser:import argparseparser = argparse.
parse_args()Now run the code with the–help option:python3 test_cli.
py –helpYou should receive a nice default help message like this:usage: test_cli.
py [-h]optional arguments: -h, –help show this help message and exitCongratulations you just made your first command-line interface!Now let’s add a welcome message to briefly let your user knows what the program does:welcome = "Practicing creating interactive command-line interfaces"parser = argparse.
parse_args()Now run the program with the -h flag.
You should be able to see your fancy welcome message.
Now let’s do something more useful.
Adding ArgumentsSuppose we are writing a program to scrape a webpage.
Some arguments we may need are the domain of the webpage –domain or -d , the option to log output to an out file –ofile or -o , and perhaps the option to print a specific number of lines of output to the console –lines or -l.
For this example, we will make the domain argument required, while the ofile and lines arguments will be optional.
We can easily add additional arguments to an argparse CLI by using .
add_argument which will let us define usage details.
We can add the required argument –domain as such:parser.
add_argument('–domain', '-d', required=True, help='domain name of the website you want to scrape.
com"')Now run the program with the -h argument to see the documentation you wrote!Since –domain is a required argument, try running the program without any flags and you will be treated to the following message:usage: test_cli.
py [-h] –domain DOMAINtest_cli.
py: error: the following arguments are required: –domain/-dIt works!Time to add our additional arguments using argparse.
If you don’t specify which arguments are required, argparse will assume they are optional.
You can also set the type of an argument, for –lines we will take an integer.
There are other useful options you can set for .
add_argument— such as action= — which you can learn more about in the official argparse documentation here.
add_argument('–ofile', '-o', help='define output file to save results of stdout.
add_argument('–lines', '-l', help='number of lines of output to print to the console"', type=int)Now test your code to make sure everything is working properly.
A simple way to do this is by storing the values of the arguments as variables, and then printing these values.
args = parser.
parse_args()domain = args.
domainofile = args.
ofilelines = args.
linesprint("domain:", domain)print("output file:", ofile)print("lines:", lines)Note: optional arguments are stored as None by default while not in use.
Here is all my code:In ConclusionWhile this is not a comprehensive guide, it should be enough to get you thinking about command-line interfaces and improving the user experience of your scripts.
After all, what’s the point of code if nobody is able to use it.
If you have additional recommendations, tips, or resources, please share in the comments!Thanks for reading! If you enjoyed it, be sure to smash that follow button 🙂 Also be sure to check out my website, Twitter, LinkedIn, and Github.