How to Sort Command-Line Arguments in Python
Build a beginner-friendly argparse CLI that sorts numbers or words passed as arguments, with an optional reverse flag.
Python code
20 linesimport argparse
def main():
parser = argparse.ArgumentParser(description="Sort numbers or words from the command line.")
parser.add_argument("items", nargs="+", help="Items to sort (numbers or words)")
parser.add_argument("--reverse", "-r", action="store_true", help="Sort in descending order")
args = parser.parse_args()
try:
values = [float(item) for item in args.items]
except ValueError:
values = args.items
result = sorted(values, reverse=args.reverse)
print("Sorted:", result)
if __name__ == "__main__":
main()
Output
$ python sort_cli.py 5 3 8 1
Sorted: [1.0, 3.0, 5.0, 8.0]
$ python sort_cli.py banana apple cherry --reverse
Sorted: ['cherry', 'banana', 'apple']
How it works
The script uses argparse to parse command-line arguments, defining items as a variadic argument with nargs="+" to accept one or more values. It attempts to convert each item to a float using a list comprehension wrapped in a try/except; if any conversion fails, it falls back to treating them as strings. The sorted() function then sorts the values, and the --reverse flag (stored as a boolean by action="store_true") controls ascending or descending order. Finally, it prints the sorted result with a clear label.
Common mistakes
- Forgetting to include `if __name__ == "__main__":` so the script runs when executed directly
- Assuming items are always numbers; mixing numbers and words causes the fallback to string sorting
- Not using `nargs="+"` so the CLI requires at least one value
- Passing the `-r` flag as `--reverse=True` instead of just `--reverse`
Variations
- Use `parser.add_argument('--key', default=None)` to sort by a custom key function
- Add `parser.add_argument('--unique', action='store_true')` to remove duplicates with `set()` before sorting
Real-world use cases
- Sorting filenames or log lines passed to a shell script for quick inspection in a pipeline.
- Ranking numeric metrics like test scores or throughput values from a script invocation.
- Preprocessing unsorted user input in an interactive automation tool before further processing.
Sponsored
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.