Use nargs='?' (or nargs='*' if you need more than one dir)

parser.add_argument('dir', nargs='?', default=os.getcwd())

extended example:

>>> import os, argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-v', action='store_true')
_StoreTrueAction(option_strings=['-v'], dest='v', nargs=0, const=True, default=False, type=None, choices=None, help=None, metavar=None)
>>> parser.add_argument('dir', nargs='?', default=os.getcwd())
_StoreAction(option_strings=[], dest='dir', nargs='?', const=None, default='/home/vinay', type=None, choices=None, help=None, metavar=None)
>>> parser.parse_args('somedir -v'.split())
Namespace(dir='somedir', v=True)
>>> parser.parse_args('-v'.split())
Namespace(dir='/home/vinay', v=True)
>>> parser.parse_args(''.split())
Namespace(dir='/home/vinay', v=False)
>>> parser.parse_args(['somedir'])
Namespace(dir='somedir', v=False)
>>> parser.parse_args('somedir -h -v'.split())
usage: [-h] [-v] [dir]

positional arguments:
  dir

optional arguments:
  -h, --help  show this help message and exit
  -v
Answer from Vinay Sajip on Stack Overflow
🌐
Python
docs.python.org › 3 › library › argparse.html
argparse — Parser for command-line options, arguments and subcommands
For example, the command-line argument -1 could either be an attempt to specify an option or an attempt to provide a positional argument. The parse_args() method is cautious here: positional arguments may only begin with - if they look like ...
🌐
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")
Discussions

python - Is it better practice to set default values for optional argparse arguments? - Software Engineering Stack Exchange
I mention python's argparse as an example but this would apply to any CLI argument parser library for any language. Just generally speaking, at a high level, if there are a lot of optional argument... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
python - How to make an optional value for argument using argparse? - Stack Overflow
I am creating a python script where I want to have an argument that manipulates how many search results you get as output. I've currently named the argument --head. This is the functionality I'd li... More on stackoverflow.com
🌐 stackoverflow.com
python - Argparse: Required arguments listed under "optional arguments"? - Stack Overflow
NB: per Christophe Vu-Brugier, ... from Python version 3.10. by default there're 2 argument groups in parser._action_groups: positional arguments and named arguments (titled 'optional arguments'). you can add your named optional arguments to the existing 'optional arguments' group, and required named arguments to a new 'required arguments' group. After that you can re-order groups: Copyimport argparse parser = ... More on stackoverflow.com
🌐 stackoverflow.com
argparse - checking for optional argument

You are not using argparse correctly - the arguments are not set on the parser, but on another object that is returned by the parse_args method.

What you should be doing is this:

parser.add_argument("-f", "--filename", help="set output filename")
args = parser.parse_args()
if args.filename is None:
    ...

Few notes:

  • action="store" is the default, specifying it does nothing useful

  • You probably want to use parse_args instead of parse_known_args, because it is simpler to use and raising arror if unknown argument is specified is what you want

  • argparse documentation will tell you all of this and much more, it also has a lot of examples

More on reddit.com
🌐 r/learnpython
6
2
March 2, 2019
Top answer
1 of 4
1220

Use nargs='?' (or nargs='*' if you need more than one dir)

parser.add_argument('dir', nargs='?', default=os.getcwd())

extended example:

>>> import os, argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-v', action='store_true')
_StoreTrueAction(option_strings=['-v'], dest='v', nargs=0, const=True, default=False, type=None, choices=None, help=None, metavar=None)
>>> parser.add_argument('dir', nargs='?', default=os.getcwd())
_StoreAction(option_strings=[], dest='dir', nargs='?', const=None, default='/home/vinay', type=None, choices=None, help=None, metavar=None)
>>> parser.parse_args('somedir -v'.split())
Namespace(dir='somedir', v=True)
>>> parser.parse_args('-v'.split())
Namespace(dir='/home/vinay', v=True)
>>> parser.parse_args(''.split())
Namespace(dir='/home/vinay', v=False)
>>> parser.parse_args(['somedir'])
Namespace(dir='somedir', v=False)
>>> parser.parse_args('somedir -h -v'.split())
usage: [-h] [-v] [dir]

positional arguments:
  dir

optional arguments:
  -h, --help  show this help message and exit
  -v
2 of 4
105

As an extension to @VinaySajip answer. There are additional nargs worth mentioning.

  1. parser.add_argument('dir', nargs=1, default=os.getcwd())

N (an integer). N arguments from the command line will be gathered together into a list

  1. parser.add_argument('dir', nargs='*', default=os.getcwd())

'*'. All command-line arguments present are gathered into a list. Note that it generally doesn't make much sense to have more than one positional argument with nargs='*', but multiple optional arguments with nargs='*' is possible.

  1. parser.add_argument('dir', nargs='+', default=os.getcwd())

'+'. Just like '*', all command-line args present are gathered into a list. Additionally, an error message will be generated if there wasn’t at least one command-line argument present.

  1. parser.add_argument('dir', nargs=argparse.REMAINDER, default=os.getcwd())

argparse.REMAINDER. All the remaining command-line arguments are gathered into a list. This is commonly useful for command line utilities that dispatch to other command line utilities

If the nargs keyword argument is not provided, the number of arguments consumed is determined by the action. Generally this means a single command-line argument will be consumed and a single item (not a list) will be produced.

Edit (copied from a comment by @Acumenus) nargs='?' The docs say: '?'. One argument will be consumed from the command line if possible and produced as a single item. If no command-line argument is present, the value from default will be produced.

🌐
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 ...
🌐
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 - They typically start with — or –. In our example, let’s add an optional argument –discount to apply a percentage discount on the total price. ... import argparse # Predefined catalog of items and their prices ITEM_CATALOG = { "apple": ...
🌐
NashTech Blog
blog.nashtechglobal.com › home › python argparse: parser for command-line options, arguments and sub-commands
Python Argparse: Parser for command-line options, arguments and sub-commands - NashTech Blog
March 8, 2021 - Now, you have successfully created your first command line argument with argparse. ... python pythonTest.py --help Output: usage: pythonTest.py [-h] echo positional arguments: echo optional arguments: -h, --help show this help message and exit
🌐
W3docs
w3docs.com › python
Argparse optional positional arguments? | W3Docs
Argparse optional positional arguments in a Python script ... import argparse parser = argparse.ArgumentParser() parser.add_argument("input_file", nargs='?', default="default.txt") parser.add_argument("output_file", nargs='?', default="output.txt") args = parser.parse_args() print(args.input_file) print(args.output_file)
Find elsewhere
🌐
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)
🌐
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.
🌐
ZetCode
zetcode.com › python › argparse
Python argparse - parsing command line arguments in Python with argparse module
September 24, 2024 - The example names the expected value value. The default name is V. $ metavar.py -h usage: metavar.py [-h] -v value optional arguments: -h, --help show this help message and exit -v value computes cube for the given value · The given name is shown in the help output. The append action allows to group repeating options. ... #!/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}!')
🌐
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. If the value cannot be converted to an integer, a TypeError will occur. ... If the arguments are not required, we call them optional arguments.
🌐
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
🌐
Tutorial Reference
tutorialreference.com › python › examples › faq › python-how-to-set-default-value-or-specified-value-in-argparse
How to use Python argparse: Default Values, Optional Arguments, and nargs='?' | Tutorial Reference
When working with argparse, these three arguments are often used together to define optional arguments with defaults: nargs='?': This makes the command-line argument optional.
🌐
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)
🌐
Read the Docs
stackless.readthedocs.io › en › 2.7-slp › library › argparse.html
15.4. argparse — Parser for command-line options, arguments and sub-commands — Stackless-Python 2.7.15 documentation
For example, consider a file named ... python myprogram.py --help usage: myprogram.py [-h] [--foo FOO] optional arguments: -h, --help show this help message and exit --foo FOO foo help $ cd .....
Top answer
1 of 7
505

Parameters starting with - or -- are usually considered optional. All other parameters are positional parameters and as such required by design (like positional function arguments). It is possible to require optional arguments, but this is a bit against their design. Since they are still part of the non-positional arguments, they will still be listed under the confusing header “optional arguments” even if they are required. The missing square brackets in the usage part however show that they are indeed required.

See also the documentation:

In general, the argparse module assumes that flags like -f and --bar indicate optional arguments, which can always be omitted at the command line.

Note: Required options are generally considered bad form because users expect options to be optional, and thus they should be avoided when possible.

That being said, the headers “positional arguments” and “optional arguments” in the help are generated by two argument groups in which the arguments are automatically separated into. Now, you could “hack into it” and change the name of the optional ones, but a far more elegant solution would be to create another group for “required named arguments” (or whatever you want to call them):

Copyparser = 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'])
Copyusage: [-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
2 of 7
138

Since I prefer to list required arguments before optional, I hack around it via:

Copyparser = argparse.ArgumentParser()
parser._action_groups.pop()
required = parser.add_argument_group('required arguments')
optional = parser.add_argument_group('optional arguments')
required.add_argument('--required_arg', required=True)
optional.add_argument('--optional_arg')
return parser.parse_args()

and this outputs:

Copyusage: main.py [-h] --required_arg REQUIRED_ARG [--optional_arg OPTIONAL_ARG]

required arguments:
  --required_arg REQUIRED_ARG

optional arguments:
  --optional_arg OPTIONAL_ARG

I can live without -h, --help showing up in the optional arguments group.

🌐
Reddit
reddit.com › r/learnpython › argparse - checking for optional argument
r/learnpython on Reddit: argparse - checking for optional argument
March 2, 2019 -

So I currently have the following code for processing arguments with argparse:

import argparse  # Processing arguments


filename = ""
parser = argparse.ArgumentParser(description="Convert quantum circuits into different environments")


def main():
    process_args()
    set_output_filename()


def process_args():
    parser.add_argument("input_format", help="input format of your script", choices=('projectq','qutip'))
    parser.add_argument("output_format", help="output format of your script", choices=('projectq','qutip'))
    parser.add_argument("-f", "--filename", help="set output filename", action="store")
    parser.parse_known_args()


def set_output_filename():
    if parser.filename is None:
        print("No input filename!")
    else:
        print("Input filename!")

Which, in theory, should check if the -f flag was used and do something different whether or not it was. However, I get the following:

PS C:\Users\hyper\Documents\dissertation> py .\convertqc.py qutip projectq --filename test                              Traceback (most recent call last):
File ".\convertqc.py", line 35, in <module>                                                                               main()
File ".\convertqc.py", line 17, in main                                                                                   set_output_filename()
File ".\convertqc.py", line 28, in set_output_filename                                                                    if parser.filename is None:
AttributeError: 'ArgumentParser' object has no attribute 'filename'

Based on some research the "if is None" check should be handling that? Not sure what's gone wrong?

Thanks in advance