Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a command line argument act as either a flag or a parsed value? [duplicate]

How do I specify that a parsed argument should be:

  • False if not specified
  • True if present (with no value)
  • or the specified value

For example I would like the following to happen:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--the_arg", ...)

print(parser.parse_args(["--the_arg"]).the_arg)              # should print True
print(parser.parse_args([]).the_arg)                         # should print False
print(parser.parse_args(["--the_arg", "my_value"]).the_arg)  # should print "my_value"
like image 575
Scott Morken Avatar asked Jan 31 '26 19:01

Scott Morken


1 Answers

The solution is to specify all of the nargs, const, and default parameters of parser.add_argument

This works:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--the_arg", nargs="?", const=True, default=False)

print(parser.parse_args(["--the_arg"]).the_arg) #prints True
print(parser.parse_args().the_arg) #prints False
print(parser.parse_args(["--the_arg", "my_value"]).the_arg) #prints "my_value"
like image 63
Scott Morken Avatar answered Feb 03 '26 07:02

Scott Morken



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!