🌐
Python documentation
docs.python.org › 3 › howto › argparse.html
Argparse Tutorial — Python 3.14.4 documentation
author, Tshepang Mbambo,. This tutorial is intended to be a gentle introduction to argparse, the recommended command-line parsing module in the Python standard library. Concepts: Let’s show the sor...
🌐
Real Python
realpython.com › command-line-interfaces-python-argparse
Build Command-Line Interfaces With Python's argparse – Real Python
December 14, 2024 - When building Python command-line interfaces (CLI), Python’s argparse module offers a comprehensive solution. You can use argparse to create user-friendly command-line interfaces that parse arguments and options directly from the command line. This tutorial guides you through organizing CLI projects, adding arguments and options, and customizing your CLI’s behavior with argparse.
🌐
Stackify
stackify.com › python-argparse-definition-how-to-use-and-best-practices
Python argparse: Definition, How to Use, and Best Practices - Stackify
February 4, 2025 - Once you’ve set up argparse, the next step is to define the arguments your script will accept. argparse makes it easy to work with both required and optional inputs, specify argument types, and provide default values when necessary. Before diving deep, it’s important to understand that command-line arguments fall into two main categories: Positional arguments, which are commonly known as arguments. Optional arguments, which are also known as options, flags, or switches. For instance, in python organizer.py /path/to/directory –verbose, the –verbose flag is an optional argument.
🌐
Python
docs.python.org › 3 › library › argparse.html
argparse — Parser for command-line options, arguments and subcommands
Source code: Lib/argparse.py Tutorial: This page contains the API reference information. For a more gentle introduction to Python command-line parsing, have a look at the argparse tutorial. The arg...
🌐
Medium
medium.com › @tushar_aggarwal › easy-argparse-a-guide-to-handling-command-line-arguments-9cdf62ff46db
Easy argparse: A guide to handling command-line arguments | by Tushar Aggarwal | Medium
July 3, 2023 - Argparse is an indispensable tool in the Python developer’s toolkit, allowing you to create user-friendly and powerful command-line interfaces for your applications. By following this comprehensive hands-on tutorial, you can now harness the power of argparse to create sophisticated CLIs and enhance your Python applications.
🌐
Python
docs.python.org › 3 › library › index.html
The Python Standard Library — Python 3.14.4 documentation
argparse — Parser for command-line options, arguments and subcommands · optparse — Parser for command line options · getpass — Portable password input · fileinput — Iterate over lines from multiple input streams · curses — Terminal ...
🌐
DataCamp
datacamp.com › tutorial › python-argparse
Master Python's argparse Module: Build Better CLIs | DataCamp
December 3, 2024 - In this tutorial, learn how to parse one or more arguments from the command-line or terminal using the getopt, sys, and argparse modules. ... Learn how you can execute a Python script from the command line, and also how you can provide command line arguments to your script.
🌐
Read the Docs
python.readthedocs.io › fr › latest › howto › argparse.html
Argparse Tutorial — documentation Python 3.7.0a0
This tutorial is intended to be a gentle introduction to argparse, the recommended command-line parsing module in the Python standard library.
Find elsewhere
🌐
DEV Community
dev.to › taikedz › ive-parked-my-side-projects-3o62
Argument parsing and subparsers in Python - DEV Community
October 27, 2022 - #!/usr/bin/env python3 import argparse # Some fictional machine API - split the logic into modules import power import engine def parse_app_args(args=None): parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(dest="cmd") # Farming out the subparser definitionss to their respective modules # So each module can define its parsing options itself power.setup_args(subparsers) engine.setup_args(subparsers) return parser.parse_args(args) def main(): parsed_args = parse_app_args() # We make a point of moving subcommand implementations to their own files, # to decluttrer this main file command_map = { "power": power.run, "engine": engine.run, } # Because the parser will only accept values for the named subparser, # we can consider the check has already been done for us :-) command_map[parsed_args.cmd](parsed_args) if __name__ == "__main__": main()
🌐
PyPA
bootstrap.pypa.io › get-pip.py
get-pip.py # script
# # If you're wondering how this ...a.io/pip/{}.{}/get-pip.py instead.".format(*this_python), ] print("ERROR: " + " ".join(message_parts)) sys.exit(1) import os.path import pkgutil import shutil import tempfile import argparse import importlib from base64 import b85decode def ...
🌐
Homebrew
formulae.brew.sh › formula
homebrew-core — Homebrew Formulae
1 week ago - This is a listing of all packages available from the core tap via the Homebrew package manager for macOS and Linux
🌐
GitHub
gist.github.com › a47460dd055a2bd69f94
python argparse example · GitHub
python argparse example · Raw · argparse_example.py · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
GeeksforGeeks
geeksforgeeks.org › python › command-line-option-and-argument-parsing-using-argparse-in-python
Command-Line Option and Argument Parsing using argparse in Python - GeeksforGeeks
July 12, 2025 - Command line arguments are those values that are passed during the calling of the program along with the calling statement. Usually, python uses sys.argv array to deal with such arguments but here we describe how it can be made more resourceful and user-friendly by employing argparse module.
🌐
Grimoire
grimoire.carcano.ch › the grimoire of a modern linux professional › blog › pillars › scripting › python argparse tutorial – argparse howto
Python Argparse Tutorial - Argparse HowTo
October 28, 2025 - The Python Argparse Tutorial - Argparse HowTo post provides a practical example of how to parse command line parameters and options using the argparse module
🌐
Apiyi.com Blog
help.apiyi.com › home
5-Step Complete Tutorial for Accessing Nano Banana Pro Image API Using OpenClaw - Apiyi.com Blog
March 11, 2026 - #!/usr/bin/env python3 """Nano Banana Pro Image Editing Script - OpenClaw Skill (Gemini Native Format)""" import os, json, base64, argparse, requests from datetime import datetime API_KEY = os.environ.get("APIYI_API_KEY", "") API_BASE = "https://api.apiyi.com/v1beta/models" def edit_image(instruction, image_url, extra_images=None): url = f"{API_BASE}/gemini-3-pro-image-preview:generateContent" headers = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"} # Build multimodal parts in Gemini native format parts = [{"text": instruction}] # Convert image URL to base64 inline
🌐
Python
docs.python.org › 3 › library › collections.html
collections — Container datatypes
import os, argparse defaults = {'color': 'red', 'user': 'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = {k: v for k, v in vars(namespace).items() if v is not None} combined = ChainMap(command_line_args, os.environ, defaults) print(combined['color']) print(combined['user'])
Top answer
1 of 16
481

Here's the way I do it with argparse (with multiple args):

parser = argparse.ArgumentParser(description='Description of your program')
parser.add_argument('-f','--foo', help='Description for foo argument', required=True)
parser.add_argument('-b','--bar', help='Description for bar argument', required=True)
args = vars(parser.parse_args())

args will be a dictionary containing the arguments:

if args['foo'] == 'Hello':
    # code here

if args['bar'] == 'World':
    # code here

In your case simply add only one argument.


Editor's note: The docs say this:

Note: Required options are generally considered bad form because users expect options to be optional, and thus they should be avoided when possible.

Use positional arguments instead, e.g. as shown in @mightypile's answer.

2 of 16
319

My understanding of the question is two-fold. First, the simplest possible argparse example. Of course, to be dead-simple, it's got to be a toy example, i.e. all overhead with little power, but it might get you started.

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("a")
args = parser.parse_args()

if args.a == 'magic.name':
    print('You nailed it!')

But this positional argument is now required. If you leave it out when invoking this program, you'll get an error about missing arguments. This leads me to the second part of the question. You seem to want a single optional argument without a named label (the --option labels). My suggestion would be to modify the code above as follows:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("a", nargs='?')
args = parser.parse_args()

if args.a is None:
    print('I can tell that no argument was given and I can deal with that here.')
elif args.a == 'magic.name':
    print('You nailed it!')
else:
    print(args.a)

There may well be a more elegant solution, but this works and is minimalist.

Note: If you want a different default value instead of None, use the default parameter to .add_argument.

🌐
GitHub
gist.github.com › abalter › 605773b34a68bb370bf84007ee55a130
Python Aargparsing Examples · GitHub
parser = argparse.ArgumentParser(description='Foo') parser.add_argument('-o', '--output', help='Output file name', default='stdout') requiredNamed = parser.add_argument_group('required named arguments') requiredNamed.add_argument('-i', '--input', help='Input file name', required=True) parser.parse_args(['-h'])
🌐
Mimo
mimo.org › glossary › python › argparse
Python argparse: Syntax, Usage, and Examples
Learn how to use Python argparse to build command-line tools with flags, defaults, types, subcommands, and input validation.