argparse is the way to go. Here is a short summary of how to use it:

1) Initialize

import argparse

# Instantiate the parser
parser = argparse.ArgumentParser(description='Optional app description')

2) Add Arguments

# Required positional argument
parser.add_argument('pos_arg', type=int,
                    help='A required integer positional argument')

# Optional positional argument
parser.add_argument('opt_pos_arg', type=int, nargs='?',
                    help='An optional integer positional argument')

# Optional argument
parser.add_argument('--opt_arg', type=int,
                    help='An optional integer argument')

# Switch
parser.add_argument('--switch', action='store_true',
                    help='A boolean switch')

3) Parse

args = parser.parse_args()

4) Access

print("Argument values:")
print(args.pos_arg)
print(args.opt_pos_arg)
print(args.opt_arg)
print(args.switch)

5) Check Values

if args.pos_arg > 10:
    parser.error("pos_arg cannot be larger than 10")

Usage

Correct use:

$ ./app 1 2 --opt_arg 3 --switch

Argument values:
1
2
3
True

Incorrect arguments:

$ ./app foo 2 --opt_arg 3 --switch
usage: convert [-h] [--opt_arg OPT_ARG] [--switch] pos_arg [opt_pos_arg]
app: error: argument pos_arg: invalid int value: 'foo'

$ ./app 11 2 --opt_arg 3
Argument values:
11
2
3
False
usage: app [-h] [--opt_arg OPT_ARG] [--switch] pos_arg [opt_pos_arg]
convert: error: pos_arg cannot be larger than 10

Full help:

$ ./app -h

usage: app [-h] [--opt_arg OPT_ARG] [--switch] pos_arg [opt_pos_arg]

Optional app description

positional arguments:
  pos_arg            A required integer positional argument
  opt_pos_arg        An optional integer positional argument

optional arguments:
  -h, --help         show this help message and exit
  --opt_arg OPT_ARG  An optional integer argument
  --switch           A boolean switch
Answer from Andrzej Pronobis on Stack Overflow
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ argparse.html
argparse โ€” Parser for command-line options, arguments and subcommands
This default is almost always desirable because it will make the help messages match the string that was used to invoke the program on the command line. However, to change this default behavior, another value can be supplied using the prog= argument to ArgumentParser: >>> parser = argparse.ArgumentParser(prog='myprogram') >>> parser.print_help() usage: myprogram [-h] options: -h, --help show this help message and exit
Top answer
1 of 15
475

argparse is the way to go. Here is a short summary of how to use it:

1) Initialize

import argparse

# Instantiate the parser
parser = argparse.ArgumentParser(description='Optional app description')

2) Add Arguments

# Required positional argument
parser.add_argument('pos_arg', type=int,
                    help='A required integer positional argument')

# Optional positional argument
parser.add_argument('opt_pos_arg', type=int, nargs='?',
                    help='An optional integer positional argument')

# Optional argument
parser.add_argument('--opt_arg', type=int,
                    help='An optional integer argument')

# Switch
parser.add_argument('--switch', action='store_true',
                    help='A boolean switch')

3) Parse

args = parser.parse_args()

4) Access

print("Argument values:")
print(args.pos_arg)
print(args.opt_pos_arg)
print(args.opt_arg)
print(args.switch)

5) Check Values

if args.pos_arg > 10:
    parser.error("pos_arg cannot be larger than 10")

Usage

Correct use:

$ ./app 1 2 --opt_arg 3 --switch

Argument values:
1
2
3
True

Incorrect arguments:

$ ./app foo 2 --opt_arg 3 --switch
usage: convert [-h] [--opt_arg OPT_ARG] [--switch] pos_arg [opt_pos_arg]
app: error: argument pos_arg: invalid int value: 'foo'

$ ./app 11 2 --opt_arg 3
Argument values:
11
2
3
False
usage: app [-h] [--opt_arg OPT_ARG] [--switch] pos_arg [opt_pos_arg]
convert: error: pos_arg cannot be larger than 10

Full help:

$ ./app -h

usage: app [-h] [--opt_arg OPT_ARG] [--switch] pos_arg [opt_pos_arg]

Optional app description

positional arguments:
  pos_arg            A required integer positional argument
  opt_pos_arg        An optional integer positional argument

optional arguments:
  -h, --help         show this help message and exit
  --opt_arg OPT_ARG  An optional integer argument
  --switch           A boolean switch
2 of 15
215

This answer suggests optparse which is appropriate for older Python versions. For Python 2.7 and above, argparse replaces optparse. See this answer for more information.

As other people pointed out, you are better off going with optparse over getopt. getopt is pretty much a one-to-one mapping of the standard getopt(3) C library functions, and not very easy to use.

optparse, while being a bit more verbose, is much better structured and simpler to extend later on.

Here's a typical line to add an option to your parser:

parser.add_option('-q', '--query',
            action="store", dest="query",
            help="query string", default="spam")

It pretty much speaks for itself; at processing time, it will accept -q or --query as options, store the argument in an attribute called query and has a default value if you don't specify it. It is also self-documenting in that you declare the help argument (which will be used when run with -h/--help) right there with the option.

Usually you parse your arguments with:

options, args = parser.parse_args()

This will, by default, parse the standard arguments passed to the script (sys.argv[1:])

options.query will then be set to the value you passed to the script.

You create a parser simply by doing

parser = optparse.OptionParser()

These are all the basics you need. Here's a complete Python script that shows this:

import optparse

parser = optparse.OptionParser()

parser.add_option('-q', '--query',
    action="store", dest="query",
    help="query string", default="spam")

options, args = parser.parse_args()

print 'Query string:', options.query

5 lines of python that show you the basics.

Save it in sample.py, and run it once with

python sample.py

and once with

python sample.py --query myquery

Beyond that, you will find that optparse is very easy to extend. In one of my projects, I created a Command class which allows you to nest subcommands in a command tree easily. It uses optparse heavily to chain commands together. It's not something I can easily explain in a few lines, but feel free to browse around in my repository for the main class, as well as a class that uses it and the option parser

Discussions

How to parse arguments interactively from CLI
If you want to be able to get arg1 etc. from either the command line or interactively, you'll need to get rid of those required=Trues. Then you'll need to check which args you already have, and prompt for the rest. Once that's completed successfully, you can proceed with the rest of the program as usual. More on reddit.com
๐ŸŒ r/learnpython
6
1
December 17, 2021
Best Way to Parse Command Line Arguments in Python? - LambdaTest Community
Whatโ€™s the best way to python parse command line arguments? Whatโ€™s the easiest, most concise, and flexible method or library for python parse command line arguments? More on community.lambdatest.com
๐ŸŒ community.lambdatest.com
0
December 2, 2024
How do I pass my own arguments to argparse without using the command line?
If you're just talking about while you're developing/debugging, it's pretty simple. Just create a launch.json, Run and Debug tab on the left > create a launch.json file. The JSON can look something like this: { "version": "0.2.0", "configurations": [ { "name": "Python: Current File", "type": "python", "request": "launch", "program": "${file}", "console": "integratedTerminal", "args": ["-i", "input.txt", "-o", "output.txt"] } ] } main.py import sys print(sys.argv) Hit F5 (or start debugging) Output ['c:\\main.py', '-i', 'input.txt', '-o', 'output.txt'] Edit: To be clear, sys.argv was just to illustrate the point, because it's simpler and faster, but it'll work with argparse as well. More on reddit.com
๐ŸŒ r/learnpython
17
3
February 9, 2024
Cappa v0.24.0: A declarative command line parsing library
Comparison to pydantic-settings cli or pydantic-cli? More on reddit.com
๐ŸŒ r/Python
6
29
October 30, 2024
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-how-to-parse-command-line-options
Python | How to Parse Command-Line Options - GeeksforGeeks
September 13, 2022 - The argparse module can be used to parse command-line options. This module provides a very user-friendly syntax to define input of positional and keyword arguments. ... ''' Hypothetical command-line tool for searching a collection of files for ...
๐ŸŒ
Embl-community
grp-bio-it-workshops.embl-community.io โ€บ intermediate-python โ€บ 04-argparse โ€บ index.html
Parsing Command Line Arguments โ€“ Intermediate Python
July 24, 2020 - Lines changed are highlighted with # <---. import argparse parser=argparse.ArgumentParser() parser.add_argument("input_file", help="path to an input file for processing") parser.add_argument("numbers", type=int, nargs="+", # <--- help="integers to be summed") parser.add_argument("--language", ...
๐ŸŒ
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.
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ howto โ€บ argparse.html
Argparse Tutorial โ€” Python 3.14.3 documentation
argparse โ€” Parser for command-line options, arguments and subcommands ยป ยท Argparse Tutorial ยท | Theme ยท Auto ยท Light ยท Dark | 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.
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ argument-parsing-in-python
Command Line Argument Parsing in Python | DataCamp
May 16, 2019 - Learn how to parse one or more arguments from the command-line or terminal using the getopt, sys, and argparse modules in Python. Follow our step-by-step tutorial to learn more!
Find elsewhere
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ parsing-command-line-arguments-python
Parsing command-line arguments in Python - Python Morsels
September 6, 2021 - $ python3 add.py 0.1 0.02 --expected=0.12 0.12000000000000001 Expected 0.12 but got 0.12000000000000001 ยท This addition gave us a number very close to 0.12 (but not exactly 0.12) so we see an error message printed out. We can also make optional command-line arguments that don't accept a value. In this version of add.py we're accepting an optional --verbose argument: import argparse parser = argparse.ArgumentParser() parser.add_argument('x', type=float) parser.add_argument('y', type=float) parser.add_argument('--verbose', action='store_true') args = parser.parse_args() if args.verbose: print(f"Adding {args.x} and {args.y}") print(args.x + args.y)
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ python-command-line-arguments
Python Command Line Arguments: sys.argv, argparse, getopt | DigitalOcean
1 week ago - This tutorial explains how to read ... 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. For most CLIs, argparse gives you help text, types, defaults, subcommands, and clear errors without writing a custom parser...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to parse arguments interactively from cli
r/learnpython on Reddit: How to parse arguments interactively from CLI
December 17, 2021 -

Hi all,

I am working on an interactive CLI app for work to add interactive functionality to a current app we use.

Currently, the way to run it is from the terminal using args, for example:

python3 main.py --arg1 arg1 --arg2 arg2 ...

So I want it to be interactive, meaning that it will look something like:

python3 main.py

>>> enter arg1: 
>>> enter arg2: 
....

The code looks something like this:

parser = argparse.ArgumentParser()
parser.add_argument("-a1", "-arg1", required=True)
parser.add_argument("-a2", "-arg2", required=True)
parser.add_argument("-a2", "-arg2")

args = parser.parse_args()

So, I assume that in order to achieve what I want, I need to be able to add arguments to the parser while the app is already running, and only once all of the required arguments have been passed to the parser, let the app run.

What is the way to achieve this?

๐ŸŒ
Typer
typer.tiangolo.com
Typer
โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ // Now pass the NAME argument $ typer main.py run Camila Hello Camila // It works! ๐ŸŽ‰ ยท This is the simplest use case, not even using Typer internally, but it can already be quite useful for simple scripts. Note: auto-completion works when you create a Python package and run it with --install-completion or when you use the typer command.
๐ŸŒ
GitHub
github.com โ€บ XavierJiezou โ€บ python-argument-parsing
GitHub - XavierJiezou/python-argument-parsing: A summary of all Python command-line argument parsing Modules. ยท GitHub
... # 1_sys.argv.py import sys def add(a, b): return a+b if __name__ == '__main__': print(add(int(sys.argv[1]), int(sys.argv[2]))) ... getopt module is a parser for command line options whose API is designed to be familiar to users of the C ...
Author ย  XavierJiezou
๐ŸŒ
GitConnected
levelup.gitconnected.com โ€บ how-pythons-argparse-simplified-command-line-arguments-for-me-ab7af9908ec0
How Pythonโ€™s argparse Simplified Command-Line Arguments for Me | by Aman Kardam (PhD) | Level Up Coding
January 7, 2025 - Thatโ€™s when I discovered Pythonโ€™s argparse module, and honestly, it changed everything. Argparse made handling command-line arguments so much simpler, more intuitive, and way more professional. Whether youโ€™re creating a simple script or a complex tool, argparse is a lifesaver.
๐ŸŒ
Udemy
blog.udemy.com โ€บ home โ€บ how to handle command line arguments in python
How to Handle Command Line Arguments in Python - Udemy Blog
March 30, 2022 - Unlike the other two methods above where we had to write extra code, this Python module adds a standardized output to the command line interface that takes care of a lot of the work for you. It also adds verification of optional and fixed arguments, help messages, and automated error handling when an argument is used incorrectly. ... import argparse # Instantiate the parser and give it a description that will show before help parser = argparse.ArgumentParser(description='My Parser') # Add arguments to the parser parser.add_argument('--firstname', dest='firstname', type=str, help='Your first na
๐ŸŒ
LambdaTest Community
community.lambdatest.com โ€บ general discussions
Best Way to Parse Command Line Arguments in Python? - LambdaTest Community
December 2, 2024 - Whatโ€™s the best way to python parse command line arguments? Whatโ€™s the easiest, most concise, and flexible method or library for python parse command line arguments?
๐ŸŒ
Accadius
accadius.com โ€บ home โ€บ parsing variable numbers of command line arguments in a python program
Parsing Variable Numbers of Command Line Arguments in a Python Program - Accadius
March 25, 2019 - The first line creates our argument parser instance and assigns it the helpful text from d. Weโ€™re specifying the formatter_class using the built-in `RawTextHelpFormatter` so that our help text will be displayed nicely, maintaining the multiple lines I have intentionally specified. The second line is creating a simple argument to the script. The user can specify -m or --filemask, interchangeably, on the command ...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how do i pass my own arguments to argparse without using the command line?
r/learnpython on Reddit: How do I pass my own arguments to argparse without using the command line?
February 9, 2024 -

I'm working with the Tableau API because I want to automatically be able to update the password for the data connections whenever the passwords change. In the sample script that Tableau has available, they have the following code:

import argparse
import logging

import tableauserverclient as TSC


def main():
    parser = argparse.ArgumentParser(
        description="Update a connection on a datasource or workbook to embed credentials"
    )
    # Common options; please keep those in sync across all samples
    parser.add_argument("--server", "-s", help="server address")
    parser.add_argument("--site", "-S", help="site name")
    parser.add_argument(
        "--token-name",
        "-p",
        help="name of the personal access token used to sign into the server",
    )
    parser.add_argument(
        "--token-value",
        "-v",
        help="value of the personal access token used to sign into the server",
    )
    parser.add_argument(
        "--logging-level",
        "-l",
        choices=["debug", "info", "error"],
        default="error",
        help="desired logging level (set to error by default)",
    )
    # Options specific to this sample
    parser.add_argument("resource_type", choices=["workbook", "datasource"])
    parser.add_argument("resource_id")
    parser.add_argument("connection_id")
    parser.add_argument("datasource_username")
    parser.add_argument("datasource_password")

    args = parser.parse_args()

    # Set logging level based on user input, or error by default
    logging_level = getattr(logging, args.logging_level.upper())
    logging.basicConfig(level=logging_level)

    tableau_auth = TSC.PersonalAccessTokenAuth(
        args.token_name, args.token_value, site_id=args.site
    )
    server = TSC.Server(args.server, use_server_version=True)
    with server.auth.sign_in(tableau_auth):
        endpoint = {"workbook": server.workbooks, "datasource": server.datasources}.get(
            args.resource_type
        )

        update_function = endpoint.update_connection
        resource = endpoint.get_by_id(args.resource_id)
        endpoint.populate_connections(resource)
        connections = list(
            filter(lambda x: x.id == args.connection_id, resource.connections)
        )
        assert len(connections) == 1
        connection = connections[0]
        connection.username = args.datasource_username
        connection.password = args.datasource_password
        connection.embed_password = True
        print(update_function(resource, connection).__dict__)


if __name__ == "__main__":
    main()

When i copy/paste and try to run it in VS Code i get the following error:

error: the following arguments are required: resource_type, resource_id, connection_id, datasource_username, datasource_password

I get the arguments with the -- or - are optional, but how do i go about defining both the optional and required arguments with my own information without using the command line?

Top answer
1 of 5
2
If you're just talking about while you're developing/debugging, it's pretty simple. Just create a launch.json, Run and Debug tab on the left > create a launch.json file. The JSON can look something like this: { "version": "0.2.0", "configurations": [ { "name": "Python: Current File", "type": "python", "request": "launch", "program": "${file}", "console": "integratedTerminal", "args": ["-i", "input.txt", "-o", "output.txt"] } ] } main.py import sys print(sys.argv) Hit F5 (or start debugging) Output ['c:\\main.py', '-i', 'input.txt', '-o', 'output.txt'] Edit: To be clear, sys.argv was just to illustrate the point, because it's simpler and faster, but it'll work with argparse as well.
2 of 5
2
Hi,I think I understand what you are looking for: the `args` argument in the `parse_args()` method. It takes in a list of strings formatted as though its coming from the command-line. Just remember that the order of the strings matter. When you specify an option `--server` for example, the next string becomes the value for `server` value. For Example: import argparse parser = argparse.ArgumentParser() parser.add_argument(("--test") parser.add_argument("--another-option") args = parser.parse_args(args=["--test", "value", "--another-option", "another value"]) # Args will now contain this namespace: # Namespace(test='value', another_option='another value') This feature is generally used during Unit Testing as its simulating the command-line, however I believe its what you are after. However, personally, I don't think `argparse` is the right fit for this use case. I get the impression the deployment of this script is not going to use the command-line for input, and you want to hard code the input. In this case - `argparse` isn't really designed for this. In the example you gave in your post - normal Python variables/constants might be a better fit for you, as other Redditors here are trying to say. If you do need some level of flexibility, static configuration files are also good option. I won't go into them here, but just searching the internet for `python config files` can find some great resources. Additionally - environment variables are also used for more sensitive data (like passwords), to prevent them from appearing in version control and being leaked. Again a search for `python read env variables` can find a bunch of cool resources. I hope this was all helpful. I've put a link below to the `parse_args` function which explains the concepts I used further up in this post.References:- https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.parse_args
๐ŸŒ
Rosetta Code
rosettacode.org โ€บ wiki โ€บ Parse_command-line_arguments
Parse command-line arguments - Rosetta Code
February 25, 2026 - Carter 2023 Apr -- The task is called "Parse command-line arguments", but as parsing requires attaching meaning to arguments, and the task -- specification does not do so, showing them is all we can reasonably do with Ada.Command_Line; with Ada.Text_IO; procedure Show_Args is -- Empty begin -- Show_Args All_Args : for Arg in 1 ..