Why should you learn argparse?

Why should you learn argparse?

Introduction

I am constantly writing scripts, sometimes even more than creating programs, classes, and everything else that OOP has to offer. Undoubtedly, a script that doesn't require maintenance during each execution, changing variables here and there, is much better!

A confession and, at the same time, a thank you to Copilot – without it, I might have avoided or postponed the implementation of these command-line options. It handles the heavy lifting, testing the code for me to ensure everything is correct.

Now, let's dive into a practical example.

Examples

This script is used in this repository to generate a standard structure of files and folders. From my end, all that's needed is to specify the folder and subject via the command line to create the basics. This is fantastic in various ways.

The complete example can be seen here.

The relevant code block is:

if name == "__main__": 
    parser = argparse.ArgumentParser(description='Create the base of the documentation') 
    parser.add_argument('--folder', type=str, help='Folder to create the documentation') 
    parser.add_argument('--subject', type=str, help='Subject of the documentation') 
    args = parser.parse_args() 
    run(folder=args.folder, subject=args.subject)        

By simply running the script in the terminal like this:

python src/createDOCSBase.py --folder python --subject "how datetime module works"        

It will create a basic file for me to edit later.

This is a simple example of what can be achieved. You can call this in a subprocess, take a list of topics and add them. Similarly, you can import the run function into another script and generate various pre-made basic structures.

That's it for today! What do you think of the tip? Any suggestions? Let me know. ??

要查看或添加评论,请登录

社区洞察

其他会员也浏览了