Here's the way I do it with argparse (with multiple args):
parser = argparse.ArgumentParser(description='Description of your program')
parser.add_argument('-f','--foo', help='Description for foo argument', required=True)
parser.add_argument('-b','--bar', help='Description for bar argument', required=True)
args = vars(parser.parse_args())
args will be a dictionary containing the arguments:
if args['foo'] == 'Hello':
# code here
if args['bar'] == 'World':
# code here
In your case simply add only one argument.
Editor's note: The docs say this:
Note: Required options are generally considered bad form because users expect options to be optional, and thus they should be avoided when possible.
Use positional arguments instead, e.g. as shown in @mightypile's answer.
Answer from Diego Navarro on Stack OverflowVideos
Here's the way I do it with argparse (with multiple args):
parser = argparse.ArgumentParser(description='Description of your program')
parser.add_argument('-f','--foo', help='Description for foo argument', required=True)
parser.add_argument('-b','--bar', help='Description for bar argument', required=True)
args = vars(parser.parse_args())
args will be a dictionary containing the arguments:
if args['foo'] == 'Hello':
# code here
if args['bar'] == 'World':
# code here
In your case simply add only one argument.
Editor's note: The docs say this:
Note: Required options are generally considered bad form because users expect options to be optional, and thus they should be avoided when possible.
Use positional arguments instead, e.g. as shown in @mightypile's answer.
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.