The documentation for the argparse python module, while excellent I'm sure, is too much for my tiny beginner brain to grasp right now. All I want to do is "If arg is A, do this, if B do that, if none of the above show help and quit". I don't need to do math on the command line or meddle with formatting lines on the screen or change option characters.
My understanding of the question is two-fold. First, the simplest possible argparse example. Of course, to be dead-simple, it's got to be a toy example, i.e. all overhead with little power, but it might get you started.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("a")
args = parser.parse_args()
if args.a == 'magic.name':
print('You nailed it!')
But this positional argument is now required. If you leave it out when invoking this program, you'll get an error about missing arguments. This leads me to the second part of the question. You seem to want a single optional argument without a named label (the --option labels). My suggestion would be to modify the code above as follows:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("a", nargs='?')
args = parser.parse_args()
if args.a is None:
print('I can tell that no argument was given and I can deal with that here.')
elif args.a == 'magic.name':
print('You nailed it!')
else:
print(args.a)
There may well be a more elegant solution, but this works and is minimalist.
Note: If you want a different default value instead of None
, use the default
parameter to .add_argument
.