Python Forum
Usage of argparse with a single option - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Usage of argparse with a single option (/thread-8455.html)



Usage of argparse with a single option - Otbredbaron - Feb-21-2018

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


RE: Usage of argparse with a single option - camp0 - Feb-21-2018

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.")


RE: Usage of argparse with a single option - Otbredbaron - Feb-24-2018

Doc says that optparse is deprecated but it can be asily adapted that to argparse, thank you


RE: Usage of argparse with a single option - metulburr - Feb-24-2018

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