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.

Answer from Diego Navarro on Stack Overflow
🌐
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.3 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 ...
🌐
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 is created, it is generated using # `scripts/generate.py` in https://github.com/pypa/get-pip. import sys this_python = sys.version_info[:2] min_version = (3, 9) if this_python < min_version: message_parts = [ "This script does not work on Python {}.{}.".format(*this_python), "The minimum supported Python version is {}.{}.".format(*min_version), "Please use https://bootstrap.pypa.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 include_setuptools(args): """ Install setuptools only if absent, not excluded and when using Python <3.12.
🌐
Homebrew
formulae.brew.sh › formula
homebrew-core — Homebrew Formulae
3 days 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.
🌐
Apiyi.com Blog
help.apiyi.com › home
5-Step Complete Tutorial for Accessing Nano Banana Pro Image API Using OpenClaw - Apiyi.com Blog
1 month ago - #!/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
Find elsewhere
🌐
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'])
🌐
Python documentation
docs.python.org › 3 › howto › argparse.html
Argparse Tutorial — Python 3.14.3 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...
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.

🌐
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...
🌐
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.
🌐
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.
🌐
The-examples-book
the-examples-book.com › tools › python › argparse
argparse :: The Examples Book
argparse is a Python package that solves our problems by creating consistent command-line interfaces and handling the arguments necessary to make your script function. We’ll begin by showing argparse stripped down to its most basic level. The contents of this tutorial were inspired by Python’s ...
🌐
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.
🌐
PythonTest
pythontest.com › testing-argparse-apps
Testing argparse Applications | PythonTest
November 16, 2023 - I was asked recently about how to test the argument parsing bit of an application that used argparse. argparse is a built in Python library for dealing with parsing command line arguments for command line interfaces, CLI’s.
🌐
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.
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-use-argparse-to-write-command-line-programs-in-python
How To Use argparse to Write Command-Line Programs in Python | DigitalOcean
March 11, 2021 - The argparse module is a powerful ... tutorial introduced you to the foundations of argparse: you wrote a command-line interface that accepted positional and optional arguments, and exposed help text to the user....