ChatGPT解决这个技术问题 Extra ChatGPT

Python argparse command line flags without arguments

How do I add an optional flag to my command line args?

eg. so I can write

python myprog.py 

or

python myprog.py -w

I tried

parser.add_argument('-w')

But I just get an error message saying

Usage [-w W]
error: argument -w: expected one argument

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.

If you just want 1 flag to your script, sys.argv would be a whole lot easier. Unless your specifically trying to learn argparse, which is a good because its a handy module to know.
Even after I know the answer now I don't see how I could have understood it from the documentation.

S
Sabito 錆兎 stands with Ukraine

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.


@Jdog, Any idea of why this doesn't work for me? The w is always False.
for me I get w always True
u
user1767754

Adding a quick snippet to have it ready to execute:

Source: myparser.py

import argparse
parser = argparse.ArgumentParser(description="Flip a switch by setting a flag")
parser.add_argument('-w', action='store_true')

args = parser.parse_args()
print args.w

Usage:

python myparser.py -w
>> True

h
halfer

Your script is right. But by default is of None type. So it considers true of any other value other than None is assigned to args.argument_name variable.

I would suggest you to add a action="store_true". This would make the True/False type of flag. If used its True else False.

import argparse
parser = argparse.ArgumentParser('parser-name')
parser.add_argument("-f","--flag",action="store_true",help="just a flag argument")

usage

$ python3 script.py -f

After parsing when checked with args.f it returns true,

args = parser.parse_args()
print(args.f)
>>>true

O
OSA413

Here's a quick way to do it, won't require anything besides sys.. though functionality is limited:

flag = "--flag" in sys.argv[1:]

[1:] is in case if the full file name is --flag


Just logged in simply to express how BAD an idea this is in the long run. Imagine that you start out by checking if the string "--flag" is in sys.argv. Then you look at the end of sys.argv[-1] to see which file to open. All of a sudden you end up with a situation where if you try to open a file named --flag, then it will behave unexpectedly, and what's worse, is that this often ends up being a security flaw down the road, when untrusted data ends up being passed to argv. In the end, this method just shouldn't be done. Real arg parsers are just far more robust...
As mentioned, this solution is not robust at all, but it works if you need this done super quickly (e.g. for testing purposes). Definitely keep it away from production code.