how to make argument optional in python argparse

As an add-on to the selected answer:

The option to run -o without specifying a file, can be done using const combined with nargs="?".

From the docs:

When add_argument() is called with option strings (like -f or –foo)
and nargs=”?”. This creates an optional argument that can be followed
by zero or one command-line arguments. When parsing the command line,
if the option string is encountered with no command-line argument
following it, the value of const will be assumed instead. See the
nargs description for examples.

Example (with type string):

parser.add_argument('-o', '--outfile', nargs="?", const="arg_was_not_given", help='output file, in JSON format')

args = parser.parse_args()

if args.outfile is None:
    print('Option not given at all')
elif args.outfile == 'arg_was_not_given':
    print('Option given, but no command-line argument: "-o"')
elif:
    print('Option and command-line argument given: "-o <file>"')

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)