Metavar: It provides a different name for optional argument in help messages. Provide a value for the metavar keyword argument within add_argument().

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', metavar='YYY')
>>> parser.add_argument('bar', metavar='XXX')
>>> parser.parse_args('X --foo Y'.split())
Namespace(bar='X', foo='Y')
>>> parser.print_help()
usage:  [-h] [--foo YYY] XXX

positional arguments:
  XXX

optional arguments:
  -h, --help  show this help message and exit
  --foo YYY

Reference: http://www.usatlas.bnl.gov/~caballer/files/argparse/add_argument.html

Action: Arguments can trigger different actions, specified by the action argument to add_argument(). There are six built-in actions that can be triggered when an argument is encountered:

  1. store: Save the value, after optionally converting it to a different type. This is the default action taken if none is specified explicitly.

  2. store_true/store_false: Save the appropriate boolean value.

  3. store_const: Save a value defined as part of the argument specification, rather than a value that comes from the arguments being parsed. This is typically used to implement command line flags that aren’t booleans.

  4. append: Save the value to a list. Multiple values are saved if the argument is repeated.

  5. append_const: Save a value defined in the argument specification to a list.

  6. version: Prints version details about the program and then exits.

Reference: http://bioportal.weizmann.ac.il/course/python/PyMOTW/PyMOTW/docs/argparse/index.html

Answer from subhadarshi samal on Stack Overflow
🌐
Python
docs.python.org › 3 › library › argparse.html
argparse — Parser for command-line options, arguments and subcommands
By default a help action is automatically added to the parser. See ArgumentParser for details of how the output is created. 'version' - This expects a version= keyword argument in the add_argument() call, and prints version information and exits when invoked: >>> import argparse >>> parser = argparse.ArgumentParser(prog='PROG') >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0') >>> parser.parse_args(['--version']) PROG 2.0
Top answer
1 of 2
85

Metavar: It provides a different name for optional argument in help messages. Provide a value for the metavar keyword argument within add_argument().

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', metavar='YYY')
>>> parser.add_argument('bar', metavar='XXX')
>>> parser.parse_args('X --foo Y'.split())
Namespace(bar='X', foo='Y')
>>> parser.print_help()
usage:  [-h] [--foo YYY] XXX

positional arguments:
  XXX

optional arguments:
  -h, --help  show this help message and exit
  --foo YYY

Reference: http://www.usatlas.bnl.gov/~caballer/files/argparse/add_argument.html

Action: Arguments can trigger different actions, specified by the action argument to add_argument(). There are six built-in actions that can be triggered when an argument is encountered:

  1. store: Save the value, after optionally converting it to a different type. This is the default action taken if none is specified explicitly.

  2. store_true/store_false: Save the appropriate boolean value.

  3. store_const: Save a value defined as part of the argument specification, rather than a value that comes from the arguments being parsed. This is typically used to implement command line flags that aren’t booleans.

  4. append: Save the value to a list. Multiple values are saved if the argument is repeated.

  5. append_const: Save a value defined in the argument specification to a list.

  6. version: Prints version details about the program and then exits.

Reference: http://bioportal.weizmann.ac.il/course/python/PyMOTW/PyMOTW/docs/argparse/index.html

2 of 2
59

metavar is used in help messages in a place of an expected argument. See FOO is a default metavar here:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> parser.add_argument('bar')
>>> parser.parse_args('X --foo Y'.split())
Namespace(bar='X', foo='Y')
>>> parser.print_help()
usage:  [-h] [--foo FOO] bar
...

action defines how to handle command-line arguments: store it as a constant, append into a list, store a boolean value etc. There are several built-in actions available, plus it's easy to write a custom one.

🌐
Python documentation
docs.python.org › 3 › howto › argparse.html
Argparse Tutorial — Python 3.14.3 documentation
Note that we now specify a new keyword, action, and give it the value "store_true". This means that, if the option is specified, assign the value True to args.verbose. Not specifying it implies False. It complains when you specify a value, in true spirit of what flags actually are. Notice the different help text. If you are familiar with command line usage, you will notice that I haven’t yet touched on the topic of short versions of the options. It’s quite simple: import argparse parser = argparse.ArgumentParser() parser.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true") args = parser.parse_args() if args.verbose: print("verbosity turned on")
🌐
DataCamp
datacamp.com › tutorial › python-argparse
Master Python's argparse Module: Build Better CLIs | DataCamp
December 3, 2024 - This guarantees that the user offers valid input, hence avoiding mistakes or unexpected actions. The options parameter lets you specify the allowable values for an argument. Consider a script that executes multiple activities depending on a mode selected by the user. import argparse parser = argparse.ArgumentParser(description='Perform actions in different modes.') parser.add_argument('--mode', choices=['backup', 'restore', 'delete'], required=True, help='Mode of operation.') args = parser.parse_args() if args.mode == 'backup': print('Backing up data...') # Backup code here elif args.mode == 'restore': print('Restoring data...') # Restore code here elif args.mode == 'delete': print('Deleting data...') # Delete code here
🌐
Reddit
reddit.com › r/learnpython › argparse: type vs action
r/learnpython on Reddit: argparse: type vs action
January 10, 2023 -

I have just started learning Python, coming from more low level language's but have some shell scripting experiences.

I wanted to write a tool with command line arguments, and quickly found the argparse module in Python's documentation. I am prone to object oriented programming and quickly ended up in a situation with a mess of post-processing string arguments into different class instances.

My mediocre Google-Fu found multiple ways of cleanly support custom type parsing, namely using the add_argument's type or action parameters. However, no site really explained their purposes; just a bunch of examples, using either mechanism. I did not feel I got a good understanding from the docs either.

What is the purpose of these two mechanics?

I read somewhere that arguments are passed through the callable type parameter and then forwarded to the callable action parameter.

Is the type mechanism supposed to parse a string to another type, and action supposed to use that newly created type instance to do whatever magic you want to happen?

🌐
Micahrl
me.micahrl.com › blog › python-argparse-custom-actions-types
Python, argparse, and custom actions and types
As it turns out, you can write a custom action that does this modification at argument parsing time. Here’s what I ended up with (combined with my resolvepath() function listed above): class StorePathAction(argparse.Action): """Resolve paths during argument parsing""" def __call__(self, parser, namespace, values, option_string=None): if type(values) is list: paths = [resolvepath(v) for v in values] else: paths = resolvepath(values) setattr(namespace, self.dest, paths) def main(*args, **kwargs): # ...
🌐
Real Python
realpython.com › command-line-interfaces-python-argparse
Build Command-Line Interfaces With Python's argparse – Real Python
December 14, 2024 - In this example, you define VerboseStore inheriting from argparse.Action. Then you override the .__call__() method to print an informative message and set the target option in the namespace of command-line arguments. Finally, the app prints the namespace itself. Go ahead and run the following command to try out your custom action: ... $ python custom_action.py --name Python Storing Python in the --name option...
Find elsewhere
🌐
Beautiful Soup
tedboy.github.io › python_stdlib › generated › generated › argparse.Action.html
argparse.Action — Python Standard Library
class argparse.Action(option_strings, ... command line strings to Python objects. Action objects are used by an ArgumentParser to represent the information needed to parse a single argument from one or more strings from the command line....
🌐
Python Module of the Week
pymotw.com › 2 › argparse
argparse – Command line option and argument parsing. - Python Module of the Week
import argparse parser = argparse.ArgumentParser(description='Short sample app') parser.add_argument('-a', action="store_true", default=False) parser.add_argument('-b', action="store", dest="b") parser.add_argument('-c', action="store", dest="c", type=int) print parser.parse_args(['-a', '-bval', '-c', '3']) There are a few ways to pass values to single character options. The example above uses two different forms, -bval and -c val. $ python argparse_short.py Namespace(a=True, b='val', c=3) The type of the value associated with 'c' in the output is an integer, since the ArgumentParser was told to convert the argument before storing it.
🌐
Medium
kameshdubey.medium.com › argparse-module-python-a539f0da4d99
Python Argparse Module Tutorial | by Kamesh Dubey | Medium
September 6, 2023 - The action attribute in argparse specifies predefined actions for processing command-line arguments, such as storing values, counting occurrences, or executing custom functions. It dictates how the parser should handle the argument, simplifying ...
🌐
Medium
baoshangu.medium.com › python-argparse-custom-action-and-custom-type-8c8fa1e8ccb8
Python argparse custom action and custom type | by Baoshan Gu | Medium
June 18, 2021 - import os import re import argparsedef check_existing_writable_dir(parser, dir_name): if os.path.exists(dir_name) and os.path.isdir(dir_name) and os.access(dir_name, os.W_OK): return dir_name # you can return an updated value if needed. else: parser.error(f"{dir_name} is not an existing writable dir")def check_patterned_name(pattern): # you can also implment this as a class similar to PatternedName def internal_func(parser, name): if re.match(pattern, name): return name else: parser.error(f"{name} does not follow the expected pattern.") return internal_funcclass CustomAction(argparse.Action): def __init__(self, check_func, *args, **kwargs): """ argparse custom action.
🌐
ZetCode
zetcode.com › python › argparse
Python argparse - parsing command line arguments in Python with argparse module
September 24, 2024 - The append action allows to group repeating options. appending.py · #!/usr/bin/python import argparse # append action allows to group repeating # options parser = argparse.ArgumentParser() parser.add_argument('-n', '--name', dest='names', action='append', help="provides names to greet") args = parser.parse_args() names = args.names for name in names: print(f'Hello {name}!') The example produces greeting messages to all names specified with the n or name options; they can be repeated multipile times.
Top answer
1 of 2
53
def make_action(additional_arg):
    class customAction(argparse.Action):
        def __call__(self, parser, args, values, option_string=None):
            print(additional_arg)
            setattr(args, self.dest, values)
    return customAction
#...
parser.add_argument('-e', '--example', action=make_action('your arg'))
2 of 2
26

Another solution is to derive the based class argparse.Action like this:

class CustomAction(argparse.Action):
    def __init__(self,option_strings,
                 additional_arg1,additional_arg2,
                 dest=None,
                 nargs=0,
                 default=None,
                 required=False,
                 type=None,
                 metavar=None,
                 help=None):
        self._a1=additional_arg1
        self._a2=additional_arg2
        super(CustomAction, self).__init__(
            option_strings=option_strings,
            dest=dest,
            nargs=nargs,
            default=default,
            required=required,
            metavar=metavar,
            type=type,
            help=help)
    def __call__(self, parser, namespace, values, option_string=None):
        print(self._a1)
        print(self._a2)
        setattr(namespace, self.dest, values)

#........
parser.add_argument('-e', '--example', action=CustomAction, additional_arg1='your arg', additional_arg2=42)

Alternatively, supply *args and **kwargs to pass through any additional parameters to the parent constructor.

class CustomAction(argparse.Action):
    def __init__(self, option_strings, additional_arg1, additional_arg2,
                 *args, **kwargs):
        self._a1 = additional_arg1
        self._a2 = additional_arg2
        super(CustomAction, self).__init__(option_strings=option_strings,
                                           *args, **kwargs)
    def __call__(self, parser, namespace, values, option_string=None):
        print(self._a1)
        print(self._a2)
        setattr(namespace, self.dest, values)

#........
parser.add_argument('-e', '--example', action=CustomAction, additional_arg1='your arg', additional_arg2=42)
🌐
Janert
janert.me › blog › 2022 › command-line-arguments-with-pythons-argparse
Command Line Arguments with Python's Argparse Module - Philipp K. Janert, Ph.D.
November 11, 2022 - action : What to do with the argument. The default is "store", meaning that the value is stored in the object returned by parse_args(). Other possibilities include "count", which returns the number of times the option has been given on the command line, and a few others (see below).
🌐
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 - There are a number of different possible strings supported by the action parameter, but "store_true" stores the value True into the argument, if it is provided on the command line. Note that, although the argument is two words separated by a dash (upper-case), argparse makes it available to your code as args.upper_case (with an underscore separator) after you call parser.parse_args(). In general, argparse converts any dashes in the provided arguments into underscores so that you have valid Python identifiers to reference after you call parse_args().
🌐
LearnPython.com
learnpython.com › blog › argparse-module
A Guide to the Python argparse Module | LearnPython.com
March 24, 2022 - You can refer to the namespace section in Python’s documentation for further explanations. Next, we also add a description to the ArgumentParser object to explain briefly what the program does. ... Note: You might want to have a better-formatted description, depending on your needs. In this case, I set my description string as a variable called arg_desc, and then I passed it into ArgumentParser(). Assigning argparse.RawDescriptionHelpFormatter to the formatter_class parameter allows me to format the description the way I want.
🌐
GitHub
github.com › python › cpython › blob › main › Lib › argparse.py
cpython/Lib/argparse.py at main · python/cpython
get_subactions = action._get_subactions · except AttributeError: pass · else: self._indent() yield from get_subactions() self._dedent() · def _split_lines(self, text, width): text = self._whitespace_matcher.sub(' ', text).strip() # The textwrap module is used only for formatting help. # Delay its import for speeding up the common usage of argparse.
Author   python
🌐
University of New Brunswick
cs.unb.ca › ~bremner › teaching › cs2613 › books › python3-doc › library › argparse.html
argparse — Parser for command-line options, arguments and sub-commands — Python 3.9.2 documentation
You may also specify an arbitrary action by passing an Action subclass or other object that implements the same interface. The BooleanOptionalAction is available in argparse and adds support for boolean actions such as --foo and --no-foo: