Here's a parser that handles a repeated 2 argument optional - with names defined in the metavar:

parser=argparse.ArgumentParser()
parser.add_argument('-i','--input',action='append',nargs=2,
    metavar=('url','name'),help='help:')

In [295]: parser.print_help()
usage: ipython2.7 [-h] [-i url name]

optional arguments:
  -h, --help            show this help message and exit
  -i url name, --input url name
                        help:

In [296]: parser.parse_args('-i one two -i three four'.split())
Out[296]: Namespace(input=[['one', 'two'], ['three', 'four']])

This does not handle the 2 or 3 argument case (though I wrote a patch some time ago for a Python bug/issue that would handle such a range).

How about a separate argument definition with nargs=3 and metavar=('url','name','other')?

The tuple metavar can also be used with nargs='+' and nargs='*'; the 2 strings are used as [-u A [B ...]] or [-u [A [B ...]]].

Answer from hpaulj on Stack Overflow
🌐
Python
docs.python.org › 3 › library › argparse.html
argparse — Parser for command-line options, arguments and subcommands
-------------------------------- ... want it options: -h, --help show this help message and exit · RawTextHelpFormatter maintains whitespace for all sorts of help text, including argument descriptions. However, multiple newlines are replaced with one. If you wish to preserve multiple blank lines, add spaces between the newlines. ArgumentDefaultsHelpFormatter automatically adds information about default values to each of the argument help messages: >>> parser = argparse.ArgumentParser( ...
🌐
Stack Overflow
stackoverflow.com › questions › 56354490 › argparse-multiple-optional-arguments
python - argparse multiple optional arguments - Stack Overflow
parser.add_argument('regex', help='the regular expression.') parser.add_argument('infile', nargs='*', type=argparse.FileType('r'), help='the name of the file(s) to search.')
Discussions

Using the same option multiple times in Python's argparse - Stack Overflow
But I can't quite figure out how to do this using argparse. It seems that it's set up so that each option flag can only be used once. I know how to associate multiple arguments with a single option (nargs='*' or nargs='+'), but that still won't let me use the -i flag multiple times. More on stackoverflow.com
🌐 stackoverflow.com
How to set several required arguments into an optional group?
Hello: I’m trying to use the argparse module to provide the argument parsing. In my use case, I have eight positional arguments: arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8: arg1 and arg2 are required. arg3 and arg4 are a couple and optional. But if users pass in one(arg3 or arg4), they ... More on discuss.python.org
🌐 discuss.python.org
6
0
May 27, 2022
How to take set multiple variables using Python argparse, both required and optional variables?
Users don't pass parameters like that, they should pass them like this: file.py -f hello --bar test testing In this case you will have a parameter f/foo that will be passed "hello" and another one b/bar that will be passed ["test", "testing"] You set your code up like this: parser = argparse.ArgumentParser() parser.add_argument('-f', '--foo', default='def', help='foo help') parser.add_argument('-b', '--bar', nargs = '*', help='bar help') params = parser.parse_args() print(params.foo) # will be "def" if nothing passed print(params.bar) # will be empty list if nothing passed Hope this helps you get it better More on reddit.com
🌐 r/learnpython
1
1
October 12, 2016
Is it possible to use argparse to make optional positional arguments, and if not, what alternatives are available?
I don't think mutially exclusive argument groups like this are possible because there would need to be ways to disambiguate, which argparse doesn't have (see comments): https://stackoverflow.com/questions/64128714/mutually-exclusive-group-with-subgroup-argparse You could use subparsers to get something like myscript update and myscript process infile outfile You could also use argparse to read in values and do validation manually. It's probably simplest to make everything optional arguments (specified with --infile in.txt, for example) and validate those. More on reddit.com
🌐 r/pythonhelp
3
2
January 26, 2022
🌐
Fanwang Econ
fanwangecon.github.io › Py4Econ › function › args › htmlpdfr › fs_func_args_cmd.html
Python Command Line Argument Parsing Positional and Optional Arguments
December 19, 2020 - # Start parser for arguments parser = argparse.ArgumentParser() # Single letter string parameters # Note dest name over-rides full name parser.add_argument('-cta', '--cttaaaaa', dest="combo_type_a", default='e', type=str) # Multiple letters and integers # Note without dest full name is dest · ## _StoreAction(option_strings=['-cta', '--cttaaaaa'], dest='combo_type_a', nargs=None, const=None, default='e', type=<class 'str'>, choices=None, help=None, metavar=None)
🌐
Python Module of the Week
pymotw.com › 2 › argparse
argparse – Command line option and argument parsing. - Python Module of the Week
This gives you explicit control over whether options using different prefixes are aliases (such as might be the case for platform-independent command line syntax) or alternatives (e.g., using “+” to indicate turning a switch on and “-” to turn it off). In the example above, +a and -a are separate arguments, and //noarg can also be given as ++noarg, but not --noarg. $ python argparse_prefix_chars.py -h usage: argparse_prefix_chars.py [-h] [-a] [+a] [//noarg] Change the option prefix characters optional arguments: -h, --help show this help message and exit -a Turn A off +a Turn A on //no
🌐
Python documentation
docs.python.org › 3 › howto › argparse.html
Argparse Tutorial — Python 3.14.6 documentation
When using the --verbosity option, one must also specify some value, any value. The above example accepts arbitrary integer values for --verbosity, but for our simple program, only two values are actually useful, True or False. Let’s modify the code accordingly: import argparse parser = argparse.ArgumentParser() parser.add_argument("--verbose", help="increase output verbosity", action="store_true") args = parser.parse_args() if args.verbose: print("verbosity turned on")
🌐
GitHub
gist.github.com › abalter › 605773b34a68bb370bf84007ee55a130
Python Aargparsing Examples · GitHub - Gist
usage: [-h] [-o OUTPUT] -i INPUT Foo optional arguments: -h, --help show this help message and exit -o OUTPUT, --output OUTPUT Output file name required named arguments: -i INPUT, --input INPUT Input file name ... If the correspond parameter does not exist, the value is opposite of store_true/store_false. If the parameter exists, the value is store_true/store_false. So we use use store_true in the most situation. return false if parameter doesn’t exist; return true if parameter exists. That’s what we want! def fun4(): import argparse parser = argparse.ArgumentParser() parser.add_argument('--p1', action='store_true') parser.add_argument('--p2', action='store_true') parser.add_argument('--p3', action='store_false') cmd = '--p1' args = parser.parse_args(cmd.split()) print(args) if args.p1: print('p1 good') else: print('p1 bad') print('\n========Go!==========\n') fun4()
🌐
Python.org
discuss.python.org › python help
How to set several required arguments into an optional group? - Python Help - Discussions on Python.org
May 27, 2022 - In my use case, I have eight positional arguments: arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8: arg1 and arg2 are required. arg3 and arg4 are a couple and optional. But if users pass in one(arg3 or arg4), they ...
Find elsewhere
🌐
Reddit
reddit.com › r/learnpython › how to take set multiple variables using python argparse, both required and optional variables?
r/learnpython on Reddit: How to take set multiple variables using Python argparse, both required and optional variables?
October 12, 2016 -

How do you deal with multiple inputs via argparse, especially when there are default inputs and optional inputs?

Within my script file.py, users must input two parameters, which I have in a list

parameters_list = [parameter1, parameter2, parameter3]

parameter1 = ""  # normally in the script, I would set these
parameter2 = ""
parameter3 = ""

The third parameter parameter3 is a default parameter.

Now, to my mind, users could include the flags at run time python file.py --parameters = 'parameter1', 'parameter2'

parser = argparse.ArgumentParser()
parser.add_argument('parameters', nargs = '*', help = 'input program parameters')
params = parser.parse_args()

However, (1) this doesn't parse how users have input the parameters`, i.e.

--parameters = 'parameter1', 'parameter2'

(2) How do you deal with the default parameter parameter3? At the moment, this will throw at error, as the variable parameter3 has been defined in the script, but isn't defined by argparse.

🌐
Reddit
reddit.com › r/pythonhelp › is it possible to use argparse to make optional positional arguments, and if not, what alternatives are available?
r/pythonhelp on Reddit: Is it possible to use argparse to make optional positional arguments, and if not, what alternatives are available?
January 26, 2022 -

I am trying to use argparse to take arguments from user input, and I basically want them to either be able to process an infile into an output, or update the script resources. So if the user wants to use the script, they would do something like:

myscript.py "infile.txt" "path/to/output/dir"

or if they need to update, I'd like to have the option to just do the following and ignore the in/out arguments completely:

myscript.py --update

This seems like a very trivial thing but I'm not quite sure how to implement it, or if it's even possible using argparse. If it is not, what other options are available to do accomplish what I'd like to do? Thank you in advance!

🌐
Python.org
discuss.python.org › python help
Multiple optional position args with argparse.ArgumentParser - Python Help - Discussions on Python.org
February 11, 2025 - Some Unix filters accept zero, one or two positional arguments to represent inputs and outputs. I have such a script which does this. The ArgumentParser bit looks like this: parser = argparse.ArgumentParser() parser.add_argument("infile", default=None, nargs="?") parser.add_argument("outfile", default=None, nargs="?") options, _args = parser.parse_known_args() This works as expected, but the help output doesn’t look quite right to me: % heictopnm -h usage: heictopnm [-h] [infi...
Top answer
1 of 2
5

A nargs='?' flagged option works in 3 ways

Copyparser.add_argument('-d', nargs='?', default='DEF', const='CONST')

commandline:

Copyfoo.py -d value # => args.d == 'value'
foo.py -d       # => args.d == 'CONST'
foo.py          # => args.d == 'DEF'

https://docs.python.org/3/library/argparse.html#const

Taking advantage of that, you shouldn't need anything like this erroneous -d -o flag.

If you don't use the const parameter, don't use '?'

Copyparser.add_argument('--user','-u', nargs='?', const='CONST', default='default_user')
parser.add_argument('--output','-o', default='default_outfile')
parser.add_argument('--input','-i', default='default_infile')
2 of 2
0

Do you want to have something like this:

Copyimport argparse

def main():
    parser = argparse.ArgumentParser(
        description='Check-Access Reporting.',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )
    parser.add_argument(
        '-d',
        dest='discrepancy',
        action='store_true',
        help='Generate discrepancy report.',
    )
    parser.add_argument(
        '--input',
        '-i',
        default='users.txt',
        help='Input file for the report.',
    )
    parser.add_argument(
        '--output',
        '-o',
        default='reports.txt',
        help='Output file for the report.',
    )
    args = parser.parse_args()

    if args.discrepancy:
        print('Report type: {}'.format(args.report_type))
        print('Input file: {}'.format(args.input))
        print('Output file: {}'.format(args.output))
    else:
        print('Report type is not specified.')

if __name__ == '__main__':
    main()

Result of option --help:

usage: ptest_047.py [-h] [-d] [--input INPUT] [--output OUTPUT]

Check-Access Reporting.

optional arguments:
  -h, --help            show this help message and exit
  -d                    generate discrepancy report (default: False)
  --input INPUT, -i INPUT
                        input file for the report (default: users.txt)
  --output OUTPUT, -o OUTPUT
                        output file for the report (default: reports.txt)

Without any option (or missing option -d):

Report type is not specified.

With option -d:

Report type: discrepancy
Input file: users.txt
Output file: reports.txt

With -d --input input.txt --output output.txt:

Report type: discrepancy
Input file: input.txt
Output file: output.txt
🌐
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.
🌐
Python Module of the Week
pymotw.com › 3 › argparse › index.html
argparse — Command-Line Option and Argument Parsing
December 30, 2016 - If the argument allows multiple values, values will be a list even if it only contains one item. The value of option_string also depends on the original argument specification. For positional required arguments, option_string is always None. $ python3 argparse_custom_action.py Initializing ...
🌐
GoLinuxCloud
golinuxcloud.com › home › programming › the ultimate guide to python argparse: no more excuses!
The Ultimate Guide to Python Argparse: No More Excuses! | GoLinuxCloud
January 9, 2024 - In this example, running python program.py -s value --long=value2 will produce: ... Optional arguments can have default values that are used when the argument is not provided in the command line. You can set a default value using the default parameter. ... import argparse # Initialize the ArgumentParser parser = argparse.ArgumentParser(description="A program to demonstrate default values for optional arguments.") # Define optional argument with default value parser.add_argument("-n", "--name", default="John", help="Specify your name") # Parse the arguments args = parser.parse_args() # Accessing the parsed argument print(f"Hello, {args.name}")
🌐
LabEx
labex.io › tutorials › python-how-to-add-multiple-argparse-arguments-451011
How to add multiple argparse arguments | LabEx
In this tutorial, you learned how to use Python's argparse module to handle command-line arguments effectively. You explored: Basic argparse functionality and creating simple scripts · Different types of arguments: positional, optional, flags, and choices · Advanced argument configurations like multiple values and custom validation
🌐
mkaz.blog
mkaz.blog › working-with-python › argparse
Parse Command-Line Arguments with Argparse
September 19, 2025 - You can also specify nargs='?' if you want to make a positional argument optional, but you need to be careful how you combine ? and * parameters, especially if you put an optional positional parameter before another one. ... parser = argparse.ArgumentParser() parser.add_argument('filename') parser.add_argument('nums', nargs='?') args = parser.parse_args() ... $ python test.py test.txt 3 ~ Filename: test.txt ~ Nums: 3 $ python test.py test.txt ~ Filename: test.txt ~ Nums: None