As you have it, the argument w is expecting a value after -w on the command line. If you are just looking to flip a switch by setting a variable True or False, have a look here (specifically store_true and store_false)

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-w', action='store_true')

where action='store_true' implies default=False.

Conversely, you could haveaction='store_false', which implies default=True.

Answer from Jdog on Stack Overflow
🌐
Python documentation
docs.python.org › 3 › howto › argparse.html
Argparse Tutorial — Python 3.14.4 documentation
And if you don’t specify the -v flag, that flag is considered to have None value. As should be expected, specifying the long form of the flag, we should get the same output. Sadly, our help output isn’t very informative on the new ability ...
Discussions

python argparse: arg with no flag - Stack Overflow
Is there a way to not use the flag -revs when use it, like this: ... Or use argparse. From the documentation (which is python3 compliant), you can do this way: More on stackoverflow.com
🌐 stackoverflow.com
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 - argparse optional value for argument - Stack Overflow
The flag is present and has a value python example.py -t ~/some/path. How can I do this with Python argparse? More on stackoverflow.com
🌐 stackoverflow.com
May 8, 2016
Argparse: How do I add a flag that doesn't require an argument, but can take an argument optionally.
Like so: parser.add_argument("-c", nargs="?", default=value1, const=value2) If "-c" does not occur in the argument list, at all, its value will be the value supplied via the default key-word argument. If "-c" occurs but with no argument after it, its value will be the value supplied via the const key-word argument. If "-c" occurs with an argument after it, its value will be that argument. More on reddit.com
🌐 r/learnpython
8
2
July 1, 2021
🌐
Reddit
reddit.com › r/learnpython › argparse: how do i add a flag that doesn't require an argument, but can take an argument optionally.
r/learnpython on Reddit: Argparse: How do I add a flag that doesn't require an argument, but can take an argument optionally.
July 1, 2021 -

Using argparse, how do you add a flag that doesn't require an argument, but can optionally take an argument.

Desired behaviour

$ keychart -c # outputs a csv to wherever PWD the script is runing from 
$ keychart -c /home/nick/csv # outputs a csv to specified directory

At present, my code that (almost) does what I want, but won't handle being given an argument:

# 'scratch.py' 
import argparse 
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--csv", help="write results to a csv to disk", action='store_true')
print(args.csv)

# works as desired
$ python3 scratch.py -c
True

# doesn't work as desired
$ python3 scratch.py -c testo
usage: scratch.py [-h] [-c]
scratch.py: error: unrecognized arguments: testo

🌐
Python
docs.python.org › 3 › library › argparse.html
argparse — Parser for command-line options, arguments and subcommands
To keep choices user-friendly, ... formats values, or omit type and handle conversion in your application code. Formatted choices override the default metavar which is normally derived from dest. This is usually what you want because the user never sees the dest parameter. If this display isn’t desirable (perhaps because there are many choices), just specify an explicit metavar. In general, the argparse module assumes that flags like -f and ...
🌐
Bite Code
bitecode.dev › p › parameters-options-and-flags-for
Parameters, options and flags for Python scripts
July 4, 2023 - E.G: python -c "print('Wingarda Leviosum')" Wingarda Leviosum · The option print('Wingarda Leviosum') is the value that comes with -c, and you can't use -c without passing any value, that would make no sense.
🌐
GitHub
gist.github.com › thorsummoner › 9850b5d6cd5e6bb5a3b9b7792b69b0a5
argparse with --no-flag options · GitHub
argparse with --no-flag options · Raw · argparse-no-flags.py · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Educative
educative.io › answers › what-are-argparse-names-or-flags-in-python
What are argparse names or flags in Python?
The program adds another argument, radius, and leaves it as an optional argument. The add_argument() function knows that the argument radius is optional because the first argument for this function is a flag.
Find elsewhere
🌐
Google Groups
groups.google.com › g › argparse-users › c › TrtY3nTEN74
Implementing a flag option
I think you want to stick with your original "flag" type > approach, and then specify nargs='?', const='no' and default='no': > > def flag(value): > value = value.lower() > if value in ("1", "true", "yes", "on"): > return True > elif value in ("0", "false", "no", "off"): > return False > raise ValueError("unknown flag value") > > parser = argparse.ArgumentParser() > parser.add_argument("-v", "--verbose", dest="verbose", > help="Be verbose?
🌐
YouTube
youtube.com › the python oracle
Python argparse command line flags without arguments - YouTube
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn--Music by Eric Matyashttps://www.soundimage.orgTrack title: Fantasca...
Published   February 12, 2023
Views   38
🌐
CSDN
devpress.csdn.net › python › 62fd45b4c677032930803254.html
Python argparse command line flags without arguments_python_Mangs-Python
August 18, 2022 - which I take it means that it wants an argument value for the -w option. What's the way of just accepting a flag? I'm finding http://docs.python.org/library/argparse.html rather opaque on this question. As you have it, the argument w is expecting a value after -w on the command line.
🌐
This Data Guy
thisdataguy.com › 2017 › 07 › 03 › no-options-with-argparse-and-python
--no options with argparse and python | This Data Guy
July 3, 2017 - parser.add_argument( '--flag', '--no-flag', dest='flag', action=BooleanAction, help='Set flag', ) BooleanAction is just a tiny 6 lines class, defined as follow: class BooleanAction(argparse.Action): def __init__(self, option_strings, dest, nargs=None, **kwargs): super(BooleanAction, self).__init__(option_strings, dest, nargs=0, **kwargs) def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, self.dest, False if option_string.startswith('--no') else True) As you can see, it just looks at the name of the flag, and if it starts with --no, the destination will be set to False.
🌐
Python Module of the Week
pymotw.com › 2 › argparse
argparse – Command line option and argument parsing. - Python Module of the Week
This is typically used to implement command line flags that aren’t booleans. ... Save the appropriate boolean value. These actions are used to implement boolean switches. ... Save the value to a list. Multiple values are saved if the argument is repeated. ... Save a value defined in the argument specification to a list. ... Prints version details about the program and then exits. import argparse parser = argparse.ArgumentParser() parser.add_argument('-s', action='store', dest='simple_value', help='Store a simple value') parser.add_argument('-c', action='store_const', dest='constant_value', c
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-parse-boolean-values-with-argparse-in-python
How to parse boolean values with `argparse` in Python - GeeksforGeeks
April 28, 2025 - They allow users to modify the ... and flags. Parsing: This refers to the process of analyzing and interpreting the command-line arguments passed to a script. It involves breaking down the arguments into individual components and extracting the relevant information. Boolean values: These are data types that can have one of two possible values: True or False. They are often used to represent yes/no or on/off options in command-line scripts. argparse module: This is a built-in Python library that ...
🌐
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 - The store_true and store_false actions are perfect for this scenario, as shown in the Boolean Flags section. Alternatively, you could use the nargs parameter with a value of '?' to indicate that the argument is optional and doesn’t necessarily ...
🌐
LearnPython.com
learnpython.com › blog › argparse-module
A Guide to the Python argparse Module | LearnPython.com
March 24, 2022 - -------------------------------- ... Python argparse! optional arguments: -h, --help show this help message and exit -i IMAGE, --image IMAGE Path to your input image -f IMAGE_FLIP, --flip IMAGE_FLIP Path to your input image · In the next section, we will explore how to switch the default value of a boolean flag. Python supports two types of arguments: those with value and those without...
🌐
mkaz.blog
mkaz.blog › working-with-python › argparse
Parse Command-Line Arguments with Argparse
September 19, 2025 - You can also use the append action to create a list if multiple flags are passed in. parser = argparse.ArgumentParser() parser.add_argument('-c', action='append') args = parser.parse_args() print("~ C: {}".format(args.c)) ... $ python test.py ~ C: None $ python test.py -c hi ~ C: ['hi'] $ python test.py -c hi -c hello -c hey ~ C: ['hi', 'hello', 'hey'] If you only want a set of allowed values to be used, you can set the choices list, which will display an error if invalid entry.
🌐
Janert
janert.me › blog › 2022 › command-line-arguments-with-pythons-argparse
Command Line Arguments with Python's Argparse Module - Philipp K. Janert, Ph.D.
(Note that the default value for "count" is None, not 0. Use the default keyword to set the value to 0 in case the option is absent.) That’s it. This should cover all situation in which I would have considered hacking up command line handling from scratch. Of course there is more; the reference ...