There are thousands of blog posts about argparse, the built-in Python module to make your own CLI.
Why would it be better than "from scratch" approaches?
Argparse is actually built-in, but I sometimes read Python scripts that reinvent the wheel.
Don't get me wrong. At the end of the day, you'll do whatever you want, but you might not know this simple module that can literally save hours of work.
Building user-friendly interfaces for your commands could be tedious. You will likely have to handle various cases:
- required parameters (you can use
required=Truewhen adding arguments with argparse)
- optional parameters
- default values
- bad inputs
- documentation (e.g., usage)
And many more. You can totally code that, but using argparse will be more readable and efficient in most cases.
Let's create a file called
myscript.py and write the following inside:
#!/usr/bin/env python3 import argparse if __name__ == "__main__": parser = argparse.ArgumentParser(description="Python Client") parser.add_argument("--myoption", type=str, help="short description for myoption", default="default value") args = parser.parse_args() print(args.myoption)
Then, in the terminal:
python3 myscript.py python3 myscript.py --myoption="cool"
Definitely no, and that's the beauty of Python. There are third-party libraries that could extend command-line creation in every possible ways.
However, the built-in argparse can cover most needs while sticking to the native modules, which is sometimes lighter and easier to include in your project.