πŸ’‘ Advanced Python Concepts
Estimated reading: 3 minutes 22 views

πŸ’» Python Command-Line Arguments – Build Smart and User-Friendly CLI Tools

🧲 Introduction – Why Use Command-Line Arguments?

Command-line arguments allow your Python scripts to accept external input when they’re executed. This turns your script into a flexible, customizable tool without changing the code every time.

With command-line arguments, you can:

  • πŸ“₯ Accept filenames, flags, and options
  • πŸ§ͺ Build testable and scriptable utilities
  • πŸ“¦ Create professional-grade CLI tools

Python offers powerful libraries like sys.argv, argparse, and click to make this easy.

🎯 In this guide, you’ll learn:

  • How to use sys.argv and argparse
  • How to parse flags, arguments, and options
  • Build real-world CLI tools
  • Best practices and error handling

βœ… 1. Using sys.argv – Quick and Basic

import sys

print("Script name:", sys.argv[0])
print("Arguments:", sys.argv[1:])
$ python script.py input.txt --verbose

βœ… Output:

Script name: script.py
Arguments: ['input.txt', '--verbose']

πŸ“Œ sys.argv is a list of strings, including the script name.


🧠 Limitations of sys.argv

  • Manual parsing
  • No type checking
  • No built-in help messages

Use it for quick scripts, not for full-featured CLI apps.


🧱 2. Using argparse – Robust CLI Parsing

import argparse

parser = argparse.ArgumentParser(description="Example CLI")
parser.add_argument("filename", help="Input file name")
parser.add_argument("--verbose", action="store_true", help="Enable verbose mode")

args = parser.parse_args()

print("File:", args.filename)
print("Verbose:", args.verbose)
$ python script.py data.txt --verbose

βœ… Output:

File: data.txt
Verbose: True

πŸ’‘ argparse provides automatic help, validation, and error messages.


πŸ”§ Add More Argument Types

parser.add_argument("--count", type=int, default=1, help="Number of repetitions")

πŸ”€ Positional vs Optional Arguments

TypeSyntax ExampleRequired?
Positionalfilenameβœ… Yes
Optional--verbose❌ No

πŸ“¦ 3. Advanced CLI with argparse

parser.add_argument("--mode", choices=["dev", "prod"], required=True)
$ python cli.py --mode dev

πŸ§ͺ Combine Flags and Options

parser.add_argument("-n", "--number", type=int)
parser.add_argument("-v", "--verbose", action="store_true")

🧰 Real-World Example – CLI File Reader

# file_reader.py
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("file", help="File to read")
parser.add_argument("--lines", type=int, default=5, help="Lines to display")

args = parser.parse_args()

with open(args.file) as f:
    for i in range(args.lines):
        print(f.readline().strip())
$ python file_reader.py sample.txt --lines 3

βœ… Reads the first 3 lines of sample.txt.


πŸ’‘ Add Help and Usage Text

argparse.ArgumentParser(
    prog="mytool",
    description="Custom tool for automation",
    epilog="Thanks for using!"
)

Run:

$ python tool.py --help

βœ… Auto-generates CLI help docs.


πŸ“˜ Best Practices

βœ… Do This❌ Avoid This
Use argparse for CLI toolsParsing manually with sys.argv
Add --help descriptionsMaking flags without documentation
Validate input with type and choicesRelying on string comparisons
Group related argumentsMixing unrelated options in flat layout

πŸ“Œ Summary – Recap & Next Steps

Python command-line arguments help you parameterize your scripts, making them flexible and user-friendly. argparse is the go-to tool for robust CLI interfaces.

πŸ” Key Takeaways:

  • βœ… Use sys.argv for simple input
  • βœ… Use argparse for professional CLI tools
  • βœ… Auto-generate help, validate types, add options
  • βœ… Ideal for file readers, processors, automation tools, and system scripts

βš™οΈ Real-World Relevance:
Used in dev tools, testing scripts, deployment pipelines, and data processing tasks.


❓ FAQ – Python Command-Line Arguments

❓ What is sys.argv in Python?

βœ… A list that contains command-line arguments passed to the script.

❓ What’s the difference between sys.argv and argparse?

βœ… sys.argv is simple but manual.
βœ… argparse is a full-featured parser with validation and help.

❓ How do I make a flag in argparse?

parser.add_argument("--debug", action="store_true")

❓ Can I have multiple optional arguments?

βœ… Yes. Just add multiple add_argument() calls with -- prefix.

❓ How do I access arguments inside the script?

βœ… After parsing:

args = parser.parse_args()
print(args.filename)

Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Python Command-Line Arguments

Or Copy Link

CONTENTS
Scroll to Top