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

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

extended example:

Copy>>> 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
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.
Top answer
1 of 4
1220

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

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

extended example:

Copy>>> 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.

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
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
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
Multiple optional position args with argparse.ArgumentParser
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() pa… More on discuss.python.org
🌐 discuss.python.org
1
1
February 11, 2025
🌐
GitHub
gist.github.com › abalter › 605773b34a68bb370bf84007ee55a130
Python Aargparsing Examples · GitHub
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 - Python argparse provides several ... in a specific order · optional arguments:allows users to specify flexible inputs, such as flags (–verbose) or key-value pairs (–timeout 10)...
🌐
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

Find elsewhere
🌐
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 - Optional arguments are prefixed by one or two dashes. The argparse module considers arguments as positional or optional automatically, based on the presence or absence of that prefix.
🌐
Python Module of the Week
pymotw.com › 2 › argparse
argparse – Command line option and argument parsing. - Python Module of the Week
$ python argparse_action.py -h usage: argparse_action.py [-h] [-s SIMPLE_VALUE] [-c] [-t] [-f] [-a COLLECTION] [-A] [-B] [--version] optional arguments: -h, --help show this help message and exit -s SIMPLE_VALUE Store a simple value -c Store a constant value -t Set a switch to true -f Set a switch to false -a COLLECTION Add repeated values to a list -A Add different values to list -B Add different values to list --version show program's version number and exit $ python argparse_action.py -s value simple_value = value constant_value = None boolean_switch = False collection = [] const_collection
🌐
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 ...
🌐
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 - Optional argument requires parameter specification. # Start parser for arguments parser = argparse.ArgumentParser() # Positional argument 1st, will be stored as int parser.add_argument('esrtype', type=int, help='positional argument 1st') # Positional argument 2nd, will be stored as string
🌐
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...
🌐
Python documentation
docs.python.org › 3 › howto › argparse.html
Argparse Tutorial — Python 3.14.6 documentation
The -l in that case is known as an optional argument. That’s a snippet of the help text. It’s very useful in that you can come across a program you have never used before, and can figure out how it works simply by reading its help text.
🌐
Codemia
codemia.io › knowledge-hub › path › argparse_optional_positional_arguments
Argparse optional positional arguments?
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises
🌐
W3docs
w3docs.com › python
Argparse optional positional arguments? | W3Docs
import argparse parser = ... a video course Python - The Practical Guide</div> When you run this script, the input_file and output_file arguments are optional and will default to "default.txt" and "output.txt", respectively, ...
🌐
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
Replace strings with implicit arguments such as �fault or %prog with the standard Python syntax to use dictionaries to format strings, that is, %(default)s and %(prog)s. Replace the OptionParser constructor version argument with a call to parser.add_argument('--version', action='version', version='<the version>'). argparse — Parser for command-line options, arguments and sub-commands
🌐
Python.org
discuss.python.org › python help
Argparse conditional optional positional arguments? - Python Help - Discussions on Python.org
October 2, 2021 - When using argparse I have to add an extra step to make sure there is a input (either from stdin or file). import sys, argparse parser = argparse.ArgumentParser() parser.add_argument('infile', nargs='?', type=argparse.FileType('r'), default=sys.stdin) args = parser.parse_args() # taking input from stdin which is empty, so there is neither a stdin nor a file as argument if sys.stdin.isatty() and args.infile.name == " ": sys.exit("Please give some input") with args.infile as file: ...
🌐
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
🌐
Python.org
discuss.python.org › ideas
Allow optional before required arguments - Ideas - Discussions on Python.org
April 30, 2024 - I recently discovered you can do this in argparse: import argparse parser = argparse.ArgumentParser() parser.add_argument("a", nargs="?", default=0) parser.add_argument("b") parser.add_argument("c", nargs="?", default=0) parser.add_argument("d") parser.add_argument("args", nargs="*") args = parser.parse_args() print(args.a, args.b, args.c, args.d, *args.args) $ python test.py usage: test.py [-h] [a] b [c] d [args ...] test.py: error: the following arguments are required: b, d, args $ python t...
🌐
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 - 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.
🌐
DataCamp
datacamp.com › tutorial › python-argparse
Master Python's argparse Module: Build Better CLIs | DataCamp
December 3, 2024 - Python file.py 6 0 Error: Denominator cannot be zero. usage: file.py [-h] numerator denominator Divide two numbers. positional arguments: numerator The numerator. denominator The denominator. options: -h, --help show this help message and exit · You can also include custom error handling in your script. For instance, to manage invalid file paths: import argparse import os parser = argparse.ArgumentParser(description='Read a file and display its contents.') parser.add_argument('filepath', help='Path to the file.') args = parser.parse_args() if not os.path.exists(args.filepath): parser.error(f"The file {args.filepath} does not exist.") with open(args.filepath, 'r') as file: contents = file.read() print(contents)