Building CLIs With Command-Line Arguments
A script becomes a real tool the moment it accepts command-line arguments. Python provides three layers — sys.argv for quick scripts, argparse for production CLIs, and third-party libraries like click and typer for fancy interfaces. This chapter focuses on the first two, which cover 95% of real-world needs.
Overview
Make Scripts Tools
Turn one-off scripts into reusable command-line utilities.
Built-In Validation
argparse rejects missing/bad args automatically.
Auto Help
-h generates a polished help message for free.
Flags & Switches
Boolean toggles with action='store_true'.
Defaults & Choices
Restrict valid inputs; provide sensible fallbacks.
Syntax
- Import
systo accesssys.argv. - Use
argparse.ArgumentParser()for proper CLI parsing. - Add arguments with
add_argument(); positional vs optional via the leading--. - Parse with
parser.parse_args()and access via attribute syntax.
# Quick way
import sys
print("Script:", sys.argv[0])
print("Args :", sys.argv[1:])
# Production way
import argparse
parser = argparse.ArgumentParser(description="Greeter")
parser.add_argument("name", help="who to greet")
parser.add_argument("--shout", action="store_true",
help="shout the greeting")
args = parser.parse_args()
msg = f"Hello, {args.name}!"
print(msg.upper() if args.shout else msg)
Detailed Explanation
- sys.argv: A list of strings. Position 0 is the script path; positions 1+ are the user's arguments. Quick but no validation, no help text.
- argparse — Positional args: Required by default.
parser.add_argument('name')creates a positional argument. The user must supply it or argparse exits with an error. - argparse — Optional args: Begin the name with
-or--. Optional unless you passrequired=True. Example:--verbose. - Type conversion:
add_argument('--count', type=int)converts string input automatically. Standard types:int,float,str, file objects viaargparse.FileType(). - Flags & defaults: Use
action='store_true'for boolean flags. Usedefault=for fallback values. Usechoices=[...]to restrict valid options. - Help text:
argparseauto-generates-h/--help. Always provide a shorthelp=for every argument — your users will thank you.
Code Examples
import sys
print("name:", sys.argv[0])
print("args:", sys.argv[1:])
# usage: python script.py hello world
args: ['hello', 'world']
import argparse
p = argparse.ArgumentParser()
p.add_argument("name")
args = p.parse_args(["Riya"])
print("Hello,", args.name)
import argparse
p = argparse.ArgumentParser()
p.add_argument("--verbose", action="store_true")
args = p.parse_args(["--verbose"])
print("verbose =", args.verbose)
import argparse
p = argparse.ArgumentParser()
p.add_argument("--count", type=int, default=1)
args = p.parse_args([])
print("Count:", args.count)
args = p.parse_args(["--count", "5"])
print("Count:", args.count)
Count: 5
import argparse
p = argparse.ArgumentParser()
p.add_argument("--mode", choices=["dev","prod"], default="dev")
args = p.parse_args(["--mode", "prod"])
print("Mode:", args.mode)
import argparse
p = argparse.ArgumentParser()
p.add_argument("a", type=float)
p.add_argument("b", type=float)
p.add_argument("--op", choices=["+","-","*","/"], default="+")
a = p.parse_args(["10", "4", "--op", "/"])
result = {"+":a.a+a.b,"-":a.a-a.b,"*":a.a*a.b,"/":a.a/a.b}[a.op]
print("Result:", result)
Real-World Use Cases
DevOps Scripts
Database backups, deployments, code generators — all driven by CLI args.
Cron Jobs
Schedule scripts with arguments for environment, date range, log level.
Reproducible ML
Pass model hyper-parameters from the command line for experiments.
Build Tools
Custom build scripts accept targets and flags.
Data Exports
Convert datasets between formats via configurable CLI utilities.
Security Scans
Penetration-testing scripts take target host and port as arguments.
Notes & Pro Tips
- Use
argparsefor any script that grows beyond one or two arguments. - Always set
description=on the parser — it appears in-h. - Use
type=to convert strings into the right type automatically. - Use
required=Truefor optional arguments that must always be provided. - Use
choices=to restrict invalid inputs. - For subcommands (git-style CLIs), use
parser.add_subparsers().
Common Mistakes
- Indexing
sys.argvblindly: raisesIndexErrorwhen the user forgets an argument. - Forgetting type conversion: all args from
sys.argvare strings. - Re-implementing argparse: writing manual parsers is error-prone and unfriendly.
- No help messages: users guess what each argument means.
- Wrong dest names:
--my-flagbecomesargs.my_flag(dash → underscore). - Mixing positional and optional incorrectly: argparse expects optional flags before or after positionals — be consistent.
Practice Problems
- Problem 1: Print all command-line arguments passed to your script.
- Problem 2: Build a CLI that takes two numbers and an operator and prints the result.
- Problem 3: Use argparse to read a filename and print the file's word count.
- Problem 4: Add a
--verboseflag to a script and print extra debug info when set. - Problem 5: Build a CLI with
--moderestricted totrainorpredict. - Problem 6: Create a CLI that takes a folder path and lists all
.pyfiles inside it.
Interview Questions
- Q1. What is
sys.argvand what doessys.argv[0]contain? - Q2. Why is
argparsepreferred over manual parsing? - Q3. How do you create a positional vs optional argument in
argparse? - Q4. What does
action='store_true'do? - Q5. How do you convert a CLI argument to an integer?
- Q6. How do you build subcommands with argparse (like
git add/git commit)?
Frequently Asked Questions
- Q1: What is sys.argv?
A list of strings containing the script name and the arguments passed to it on the command line. - Q2: Why use argparse?
It validates inputs, generates help text, converts types, and prevents many bugs from rolling your own parser. - Q3: How do I make an argument optional?
Prefix the name with -- (e.g. --verbose). Optional by default unless you set required=True. - Q4: How do I create a boolean flag?
Use action='store_true' (or 'store_false'). When the flag is present, the value becomes True. - Q5: How are values converted to int/float?
Pass type=int or type=float to add_argument; argparse converts user input before storing. - Q6: How do I print help automatically?
argparse adds -h and --help by default. Provide help= for each argument to populate the auto-generated text.
Summary
Command-line arguments transform Python scripts into real tools. sys.argv covers quick one-offs, while argparse brings validation, help, types, and choices to production CLIs with a few lines of code. Master argparse and your scripts will feel as polished as the tools you use every day — and your future self will reuse them happily.
Continue Learning
Previous
Go to Previous Chapter