Python Forum

Full Version: Usage of argparse with a single option
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, I'm trying to use argparse to handle a single command line option, this is the code that I wrote:

#!/usr/bin/env python3
import argparse

parser = argparse.ArgumentParser(description='foo')
parser.add_argument("Option", choices=['true','false'] )
args = parser.parse_args()
if (args.Option == 'true'):
    print('something')
else: #then it's false
    print('something else')
I'd like to know if it's correct or there's a better way to do this
Here is how I do it

p = optparse.OptionParser()

p.add_option("-f", "--flag", dest="flag", default=False, action="store_true",
help="Help for flag.")
Doc says that optparse is deprecated but it can be asily adapted that to argparse, thank you
There is no point in doing a boolean choice as the arg would exist for true, otherwise would be false if there is no arg

parser.add_argument('-c','--clean', action='store_true', 
    help='Remove all .pyc files and __pycache__ directories')
args = vars(parser.parse_args())

if args[‘clean‘]:
    pass
args.clean is true if given -c option and is false if not given any arg or no -c arg at least

And yes dont use optparse anymore, only argparse