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
🌐
Python documentation
docs.python.org › 3 › howto › argparse.html
Argparse Tutorial — Python 3.14.4 documentation
In order to translate these strings, they must first be extracted into a .po file. For example, using Babel, run this command: $ pybabel extract -o messages.po /usr/lib/python3.12/argparse.py
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.

🌐
Real Python
realpython.com › command-line-interfaces-python-argparse
Build Command-Line Interfaces With Python's argparse – Real Python
December 14, 2024 - Add arguments and options to the parser using the .add_argument() method. Call .parse_args() on the parser to get the Namespace of arguments. As an example, you can use argparse to improve your ls_argv.py script.
🌐
Python
docs.python.org › 3 › library › argparse.html
argparse — Parser for command-line options, arguments and subcommands
By default, argparse automatically handles the internal naming and display names of arguments, simplifying the process without requiring additional configuration. As such, you do not need to specify the dest and metavar parameters. For optional arguments, the dest parameter defaults to the argument name, with underscores _ replacing hyphens -. The metavar parameter defaults to the upper-cased name. For example...
🌐
Mimo
mimo.org › glossary › python › argparse
Python argparse: Syntax, Usage, and Examples
In Python argparse, positional arguments are required by default. Optional arguments are created by adding a -- prefix: ... The --verbose flag is optional and behaves like a boolean switch. You can activate it with: ... This automatically sets args.verbose to True. Here's a complete example using positional and optional arguments:
🌐
Medium
medium.com › swlh › learning-argparse-by-example-299c3f35f2b5
Learning Argparse by Example. Implementing a very simple command-line… | by Matt Oehler | The Startup | Medium
January 7, 2020 - The random library will make it nice and easy to jumble the letters, and the re library helps to strip the punctuation from the input text. Base python should be equipped with everything else we need, so let's get started on piecing things together. We'll also be using the argparse library to make our code usable from the command line.
🌐
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 - This code utilizes the 'argparse' module to create a command-line interface for sorting integers in ascending order. It defines two command-line arguments: 'integers' to accept multiple integer values and 'accumulate' to arrange these integers ...
🌐
CRAN
cran.r-project.org › web › packages › argparse › vignettes › argparse.html
argparse Command Line Argument Parsing
If not, see <http://www.gnu.org/licenses/>. suppressPackageStartupMessages(library("argparse")) # create parser object parser <- ArgumentParser() # specify our desired options # by default ArgumentParser will add an help option parser$add_argument( "-v", "--verbose", action = "store_true", default = TRUE, help = "Print extra output [default]" ) parser$add_argument( "-q", "--quietly", action = "store_false", dest = "verbose", help = "Print little output" ) parser$add_argument( "-c", "--count", type = "integer", default = 5, help = "Number of random normals to generate [default %(default)s]", me
Find elsewhere
🌐
Python Module of the Week
pymotw.com › 2 › argparse
argparse – Command line option and argument parsing. - Python Module of the Week
In this example, the “count” argument is an integer and the “units” argument is saved as a string. If either is not provided on the command line, or the value given cannot be converted to the right type, an error is reported. $ python argparse_arguments.py 3 inches Namespace(count=3, units='inches') ...
🌐
The-examples-book
the-examples-book.com › tools › python › argparse
argparse :: The Examples Book
For argparse, the default value for type is string. Leaving out type=int would result in string concatenation instead of addition.
🌐
DataCamp
datacamp.com › tutorial › python-argparse
Master Python's argparse Module: Build Better CLIs | DataCamp
December 3, 2024 - For example, nargs=2 requires exactly two parameters. Sometimes, you want to limit an argument to a specified range of valid values. This guarantees that the user offers valid input, hence avoiding mistakes or unexpected actions. The options parameter lets you specify the allowable values for ...
🌐
GitHub
gist.github.com › abalter › 605773b34a68bb370bf84007ee55a130
Python Aargparsing Examples · GitHub
import argparse # Instantiate the parser parser = argparse.ArgumentParser(description='Optional app description')
🌐
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 - Positional arguments (as opposed to optional arguments, which we’ll explore in a subsequent section), are generally used to specify required inputs to your program. Let’s consider an example CLI that prints the fish in an aquarium tank identified by a positional tank argument.
🌐
GitHub
gist.github.com › amarao › 36327a6f77b86b90c2bca72ba03c9d3a
Example of argparse with subparsers for python · GitHub
#!/usr/bin/env python import logging import sys from pathlib import Path import argparse from argparse import ArgumentParser, Namespace from typing import Callable logger = logging.getLogger(__name__) def run_alpha(input_path: Path) -> int: logger.info(f"Running alpha for {input_path}") return 0 def run_beta(src: Path, dest: Path) -> int: logger.info(f"Running alpha with {src=} {dest=}") return 0 def _to_parser_alpha(p: ArgumentParser) -> ArgumentParser: p.add_argument("-i", "--input", type=Path, required=True) return p def _to_parser_beta(p: ArgumentParser) -> ArgumentParser: p.add_argument("
🌐
Cherry Servers
cherryservers.com › home › blog › cloud computing › how to use argparse in python to build command-line interfaces
How to Use argparse in Python | Cherry Servers
February 10, 2026 - In the above code, the positional argument named "number" is defined using argparse. The user does not need to use a flag when providing the argument value. Note: In this example, the value is expected to be an integer due to the specified type=int.
🌐
Nokia
network.developer.nokia.com › static › sr › learn › pysros › latest › argparse.html
argparse – Argument parser functions — pySROS 26.3.1 documentation
The following sections walk you through this example. The first step in using the argparse is creating an ArgumentParser object:
🌐
ZetCode
zetcode.com › python › argparse
Python argparse - parsing command line arguments in Python with argparse module
September 24, 2024 - The argparse is a standard module; we do not need to install it. A parser is created with ArgumentParser and a new parameter is added with add_argument. Arguments can be optional, required, or positional. The following example creates a simple argument parser.
🌐
PythonForBeginners
pythonforbeginners.com › home › argparse tutorial
Argparse Tutorial - PythonForBeginners.com
August 25, 2020 - The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv.
🌐
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 - Let’s explore the advanced capabilities of the argparse module to build more powerful and user-friendly CLIs. Using the Price Calculator as our example, we’ll dive into handling multiple arguments, argument groups, mutually exclusive groups, subcommands, and customizing help messages.