How to Create a CLI Tool in Python: Simple Guide
To create a CLI tool in Python, use the
argparse module to handle command-line arguments. Define commands and options, then run your script from the terminal to interact with it.Syntax
The basic syntax to create a CLI tool uses the argparse.ArgumentParser() class. You add arguments with add_argument() and parse them with parse_args().
- ArgumentParser(): Creates a parser object.
- add_argument(): Defines a command-line argument or option.
- parse_args(): Reads the arguments passed by the user.
python
import argparse parser = argparse.ArgumentParser(description='Describe your CLI tool here') parser.add_argument('name', help='Your name') args = parser.parse_args() print(f'Hello, {args.name}!')
Example
This example shows a simple CLI tool that greets the user by name and accepts an optional shout flag to print the greeting in uppercase.
python
import argparse def main(): parser = argparse.ArgumentParser(description='Greet the user') parser.add_argument('name', help='Your name') parser.add_argument('--shout', action='store_true', help='Shout the greeting') args = parser.parse_args() greeting = f'Hello, {args.name}!' if args.shout: greeting = greeting.upper() print(greeting) if __name__ == '__main__': main()
Output
Hello, Alice!
HELLO, ALICE!
Common Pitfalls
Common mistakes when creating CLI tools include:
- Not checking if the script is run as the main program using
if __name__ == '__main__'. - Forgetting to use
action='store_true'for flags that don't take values. - Not providing helpful descriptions for arguments, which makes the tool harder to use.
- Trying to parse arguments multiple times or outside the main function.
python
import argparse # Wrong: parsing arguments outside main and missing __main__ guard parser = argparse.ArgumentParser() parser.add_argument('--verbose', help='Enable verbose mode') args = parser.parse_args() print(args.verbose) # Right way: import argparse def main(): parser = argparse.ArgumentParser() parser.add_argument('--verbose', action='store_true', help='Enable verbose mode') args = parser.parse_args() print(args.verbose) if __name__ == '__main__': main()
Quick Reference
| Term | Description |
|---|---|
| ArgumentParser() | Creates the parser object for CLI arguments |
| add_argument() | Defines a command-line argument or option |
| parse_args() | Parses the arguments passed by the user |
| action='store_true' | Makes an argument a boolean flag |
| if __name__ == '__main__' | Ensures code runs only when script is executed directly |
Key Takeaways
Use argparse to handle command-line arguments easily in Python.
Always include the __main__ guard to run your CLI tool safely.
Use action='store_true' for flags that do not require values.
Provide clear descriptions for arguments to help users.
Test your CLI tool by running it from the terminal with different arguments.