Sr Technical Writer and Team Lead

Python command line arguments are values you pass to a script when you run it
from a terminal. They let you change behavior without editing code: input
files, numeric options, feature flags, and subcommands. This tutorial explains
how to read and validate Python command line arguments using sys.argv,
the argparse module (ArgumentParser), and the getopt module for
Unix-style options.
sys.argv is a list of strings where sys.argv[0] is the script name and
further items are arguments split by the shell.-a -b option strings; you handle errors
with getopt.GetoptError.add_subparsers when your tool behaves like git init or
git status, with different arguments per subcommand.python3 your_script.py.When you run:
python3 report.py input.csv --verbose
the interpreter passes three logical tokens after the script name (input.csv,
--verbose) into your program. The exact splitting rules depend on the shell,
but Python always sees a sequence of strings. Your job is to interpret that
sequence safely, reject bad input, and show usage text when users run --help.
The sys module exposes argv, a list where index 0 holds how the script was
invoked (often the script path) and remaining entries are arguments. This is the
lightweight way to read Python command line arguments when you only need a
few values.
import sys
print(type(sys.argv))
print("The command line arguments are:")
for i in sys.argv:
print(i)

For more system-specific behavior (such as sys.exit()), see the Python
documentation for the sys
module.
IndexErrorIf you read sys.argv[1] without checking length, users who omit an argument
trigger IndexError. Catch that case and print a short usage message:
import sys
def main():
if len(sys.argv) < 2:
print("Usage: python3 greet.py NAME", file=sys.stderr)
sys.exit(1)
name = sys.argv[1]
print(f"Hello, {name}")
if __name__ == "__main__":
main()
To pass structured data to functions in larger programs, it helps to know how Python groups values in lists; see Understanding Lists in Python 3.
The argparse module in Python centers on ArgumentParser. It supports
positional arguments, optional arguments (flags), types, defaults, and
subcommands. Prefer it for new CLIs so users get --help text and consistent
errors.
import argparse
parser = argparse.ArgumentParser()
parser.parse_args()

Positional arguments follow the script name in order. Optional arguments
use a prefix such as - or --. The ArgumentParser class wires both styles
in one place:
import argparse
parser = argparse.ArgumentParser(description="Process some paths.")
parser.add_argument("filename", help="input file")
parser.add_argument(
"-v",
"--verbose",
action="store_true",
help="print status messages",
)
args = parser.parse_args()
print(args.filename, args.verbose)
Read the argparse documentation and the Argparse how-to for deeper patterns.
The getopt module mirrors C getopt(). You pass a short option string and
optional long options. It returns (opts, args) where opts is a list of
(option, value) pairs and args holds remaining operands.
import getopt
import sys
argv = sys.argv[1:]
try:
opts, args = getopt.getopt(argv, "hm:d", ["help", "my_file="])
print(opts)
print(args)
except getopt.GetoptError as err:
print(err, file=sys.stderr)
sys.exit(2)

For details on option strings, see the getopt documentation.
| Topic | sys.argv |
argparse (ArgumentParser) |
getopt |
|---|---|---|---|
| Best for | Tiny scripts | Full CLIs with help and types | Unix-style flags |
| Help text | You write it | Built-in --help |
You write it |
| Validation | Manual | type=, choices=, nargs= |
Manual |
| Subcommands | Manual dispatch | add_subparsers |
Manual |
| Error style | Your exceptions | argparse errors | GetoptError |
argparseparse_args() exits the process on malformed input. Use exit_on_error=False
(Python 3.9+) if you need to catch issues without exiting:
import argparse
parser = argparse.ArgumentParser(exit_on_error=False)
parser.add_argument("--count", type=int, default=1)
try:
args = parser.parse_args(["--count", "not-a-number"])
except argparse.ArgumentError as err:
print(err)
For custom checks, call parser.error("message") inside a type= callable or
after parsing.
sys.argvValidate length and formats explicitly, print to sys.stderr, then call
sys.exit(1) for user errors.
getoptWrap getopt.getopt in try/except getopt.GetoptError as shown earlier. Exit
with a non-zero code (commonly 2) after printing usage.
When a CLI calls other programs, passing a clean argument list matters. See How To Use Subprocess To Run External Programs in Python 3.
Argparse subparsers model tools like Git: a top-level program name with subcommands that each accept their own arguments.
import argparse
def cmd_init(args):
print("init", args.path)
def cmd_status(_args):
print("status")
parser = argparse.ArgumentParser(prog="repo")
sub = parser.add_subparsers(dest="command", required=True)
p_init = sub.add_parser("init", help="create a repo")
p_init.add_argument("path")
p_init.set_defaults(func=cmd_init)
p_status = sub.add_parser("status", help="show status")
p_status.set_defaults(func=cmd_status)
args = parser.parse_args()
args.func(args)
Run python3 tool.py init ./myrepo or python3 tool.py status to exercise
each branch.
Use environment variables for API tokens, default regions, or settings your
hosting provider injects at runtime. Argparse can read os.environ when
defining defaults so flags still override the shell:
import argparse
import os
parser = argparse.ArgumentParser()
parser.add_argument(
"--theme",
default=os.environ.get("APP_THEME", "light"),
help="UI theme (default: env APP_THEME or light)",
)
args = parser.parse_args()
print(args.theme)
This pattern keeps secrets out of shell history while still allowing one-off overrides.
sys.argv[0] in Python?sys.argv[0] is the string that tells the interpreter which script is running.
It is often a path or script name. It is not a user-supplied argument in the
same sense as sys.argv[1:], which holds parameters the user passed after the
command. This matches common questions people ask about the default contents of
sys.argv.
Positional arguments are required values identified by order, such as a file
name right after the script. Optional arguments use flag prefixes (- or --)
and can be omitted when defaults apply. Optional arguments can still be
required in the argparse sense if you set required=True on that parameter.
sys.argv?Use argparse when users need --help, typed values, subcommands, or clear
error messages. Use raw sys.argv when the script accepts one or two fixed
strings and you want almost no overhead.
For optional parameters, pass required=True to add_argument. Positional
arguments are already required unless you change nargs. Remember that making
a flag “required” can surprise users; often a positional or a default from the
environment is clearer.
Yes. Set default=os.environ.get("VAR_NAME") (and optionally combine with a
literal default). Flags still win when provided. This is common on servers and
in containers where configuration arrives from the environment.
Python command line arguments tie your scripts to real workflows: batch
jobs, developer tools, and automation. Start with sys.argv for the smallest
scripts, use getopt when you must match Unix option parsing rules, and reach
for argparse with ArgumentParser and subparsers when the interface grows.
Format CLI output clearly with How To Use String Formatters in Python 3. When behavior gets complex, How To Use the Python Debugger helps you step through parsing code safely.
If you want to run Python services close to your users, deploy on DigitalOcean App Platform. You can ship a CLI-backed web app or API, bind environment-based configuration, and scale from the same Git repo you use locally. Read the App Platform product documentation for build commands, routes, and health checks. For full control over the OS and long-running jobs, Droplets give you a Linux VM where you can install Python, schedule scripts, and integrate with the rest of your stack.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
I help Businesses scale with AI x SEO x (authentic) Content that revives traffic and keeps leads flowing | 3,000,000+ Average monthly readers on Medium | Sr Technical Writer(Team Lead) @ DigitalOcean | Ex-Cloud Consultant @ AMEX | Ex-Site Reliability Engineer(DevOps)@Nutanix
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.