惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
雷峰网
雷峰网
博客园 - 叶小钗
C
Check Point Blog
F
Fortinet All Blogs
A
About on SuperTechFans
Y
Y Combinator Blog
Vercel News
Vercel News
IT之家
IT之家
V
V2EX
T
Tailwind CSS Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
The GitHub Blog
The GitHub Blog
Jina AI
Jina AI
Blog — PlanetScale
Blog — PlanetScale
罗磊的独立博客
云风的 BLOG
云风的 BLOG
U
Unit 42
博客园_首页
量子位
M
MIT News - Artificial intelligence
G
Google Developers Blog
小众软件
小众软件
N
Netflix TechBlog - Medium
P
Palo Alto Networks Blog
S
Schneier on Security
T
Tor Project blog
F
Full Disclosure
C
Cyber Attacks, Cyber Crime and Cyber Security
T
Tenable Blog
T
The Blog of Author Tim Ferriss
Spread Privacy
Spread Privacy
Engineering at Meta
Engineering at Meta
GbyAI
GbyAI
Microsoft Azure Blog
Microsoft Azure Blog
Google DeepMind News
Google DeepMind News
T
Threat Research - Cisco Blogs
Know Your Adversary
Know Your Adversary
P
Proofpoint News Feed
Security Latest
Security Latest
D
Darknet – Hacking Tools, Hacker News & Cyber Security
博客园 - 司徒正美
AWS News Blog
AWS News Blog
Simon Willison's Weblog
Simon Willison's Weblog
Recorded Future
Recorded Future
L
Lohrmann on Cybersecurity
I
Intezer
L
LangChain Blog
L
LINUX DO - 热门话题

DigitalOcean Community Tutorials

Mastering grep with Regular Expressions for Efficient Text Search It's Time to Break Up with Your Cloud: Why AI Teams are Switching We Built a Private-Document AI App to Test Platform Security. Here Is What We Could Actually Verify. PostgreSQL Explained: A Complete Beginner-to-Advanced Guide How To Install and Configure Postfix on Ubuntu How To Build a Web Application Using Flask in Python 3 Build AI Reading List with DigitalOcean Functions and Mistral How To Concatenate Strings in Python How to Allow MySQL Remote Access Securely How To Install and Use Docker on Rocky Linux How To Build a Multi-Agent AI System with Docker Agent DSPy Use Cases: Build Optimized LLM Pipelines How To Submit AJAX Forms with jQuery Build an AI-Powered GPU Fleet Optimizer with the DigitalOcean AI Platform ADK Monitor GPU Utilization in Real Time: A Complete Guide Reduce File Size of Images in Linux - CLI and GUI methods Reduce PDF File Size in Linux: Tools and Methods How To Set Up a Private Docker Registry on Ubuntu How To Troubleshoot Terraform: Errors and Fixes How to Use Go Modules Python Multiprocessing Example: Process, Pool & Queue Convert Class Components to Functional Components with React Hooks How To Install and Configure Ansible on Ubuntu LLM Tokenizers Simplified: BPE, SentencePiece, and More How To Monitor System Authentication Logs on Ubuntu How to Use Traceroute and MTR to Diagnose Network Issues How to Deploy Postgres to Kubernetes Cluster Importing Packages in Go: A Complete Guide Create RAID Arrays with mdadm on Ubuntu How To Make an HTTP Server in Go How To Set Up Time Synchronization on Ubuntu How To Use Struct Tags in Go apt-key Deprecation: Add Repositories with GPG on Ubuntu Linux ps Command: 20 Real-World Examples Python struct.pack and struct.unpack for Binary Data Deadlock in Java: Examples, Detection, and Prevention How To Use Find and Locate to Search for Files on Linux Structured Resume Skill Extraction Using Mistral-7B Inference How to Use the Python Main Function How to Set Up NemoClaw on a DigitalOcean Droplet with 1-Click Build an End-to-End RAG Pipeline for LLM Applications From Single to Multi-Agent Systems: Key Infrastructure Needs Back Up Data to Object Storage Using Restic How to Generate Videos with LTX-2.3 on DigitalOcean GPU Droplets How To Install LAMP Stack (Apache, MySQL, PHP) on Ubuntu How to Download Files with cURL How To Use Variadic Functions in Go Generate UUIDs with uuidgen on Linux How To Use EJS to Template Your Node Application How to Install Node.js on Ubuntu (Step-by-Step Guide) MongoDB Indexes: Improve Query Performance with Node.js LLM Tool Calling with DigitalOcean AI Platform and Databases What are Text Diffusion Models? - An Overview Crafting a Game from Scratch with GPT-5.4 Building Long-Term Memory in AI Agents with LangGraph and Mem0 How To Install PHP 7.4 and Set Up a Local Development Environment on Ubuntu 20.04 Build a GraphQL API in Go to Upload Files to Spaces How To Lint and Format Code with ESLint in Visual Studio Code Train YOLO26 for Retail Object Detection on DigitalOcean GPUs How To Work with JSON in MySQL How to Use the JavaScript .map() Method Building a Scalable App with MongoDB Using DigitalOcean's MCP Server How to Create an SSH Key in Linux: Easy Step-by-Step Guide Measure MySQL Query Performance with mysqlslap How To Use *args and **kwargs in Python 3 Nemotron 3 helped me find the perfect dish rack? A2A vs MCP - How These AI Agent Protocols Actually Differ How To Install and Manage Supervisor Docker Container Images with Watchtower on Ubuntu Getting Started with Qwen3.5 Vision-Language Models How To Create a New Sudo-Enabled User on Ubuntu How to Use Ansible to Install and Set Up Docker on Ubuntu How To Enable Remote Desktop Protocol Using xrdp on Ubuntu 22.04 How To Convert a String to a List in Python How To Check If a String Contains Another String in Python How to Read a Properties File in Python Mastering Grep command in Linux/Unix: A Beginner's Tutorial Understanding Python Data Types How to Implement a Stack in C With Code Examples Python os.system() vs subprocess: Run System Commands How To Install and Use Docker Compose on Ubuntu How to Add and Delete Users on Ubuntu How To Order Query Results in Laravel Eloquent How To Define and Use Handlers in Ansible Playbooks How To Install and Use SQLite on Ubuntu How To Install and Use Homebrew on macOS How To Manage DateTime with Carbon in Laravel and PHP How To Install Git on Ubuntu How To Install and Secure Redis on Ubuntu How To Build and Install Go Programs on Linux Using ldflags to Set Version Information for Go Applications How To Build a Node.js Application with Docker How To Add JavaScript to HTML How To Reset Your MySQL or MariaDB Root Password How To Add Images in Markdown How To Set Up a Production Elasticsearch Cluster with Ansible How To Set Up a Firewall Using firewalld on CentOS Understanding Systemd Units and Unit Files How To Set Up Replication in MySQL How To Use the .htaccess File
Python Command Line Arguments: sys.argv, argparse, getopt
Anish Singh Walia · 2022-08-04 · via DigitalOcean Community Tutorials

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.

Key takeaways

  • sys.argv is a list of strings where sys.argv[0] is the script name and further items are arguments split by the shell.
  • For most CLIs, argparse gives you help text, types, defaults, subcommands, and clear errors without writing a custom parser.
  • getopt fits legacy or C-style -a -b option strings; you handle errors with getopt.GetoptError.
  • Combine argparse with environment variables when secrets or defaults should come from the shell profile or your hosting platform.
  • Use argparse add_subparsers when your tool behaves like git init or git status, with different arguments per subcommand.

Prerequisites

What are command line arguments in Python?

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.

Accessing command line arguments with sys.argv

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)

Output listing sys.argv entries for a sample
run

For more system-specific behavior (such as sys.exit()), see the Python documentation for the sys module.

Manual parsing and IndexError

If 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.

Parsing command line arguments with the argparse module

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()

Running a minimal argparse script with no
arguments

Positional and optional arguments

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.

Using the getopt module for Unix-style options

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)

Sample run of getopt parsing short and long
options

For details on option strings, see the getopt documentation.

Comparing sys.argv, argparse, and getopt

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

Handling missing or invalid arguments

With argparse

parse_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.

With sys.argv

Validate length and formats explicitly, print to sys.stderr, then call sys.exit(1) for user errors.

With getopt

Wrap 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.

Building multi-command CLIs with argparse subparsers

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.

Combining argparse with environment variables

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.

Frequently asked questions

1. What is 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.

2. What is the difference between positional and optional arguments in argparse?

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.

3. When should I use argparse instead of 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.

4. How do I make an argparse argument required?

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.

5. Can I use argparse with environment variables?

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.

Conclusion

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.

Build and ship Python CLIs on DigitalOcean

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.

References

Still looking for an answer?

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.