Python Forum
Usage of argparse with a single option
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Usage of argparse with a single option
#1
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
Reply
#2
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.")
Reply
#3
Doc says that optparse is deprecated but it can be asily adapted that to argparse, thank you
Reply
#4
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
Recommended Tutorials:
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Bug argparse io issue pyDream 1 94 Yesterday, 06:04 PM
Last Post: snippsat
  Not able to figure out what is wrong with argparse radioactive9 31 8,204 Mar-16-2022, 07:50 PM
Last Post: deanhystad
  argparse --help in one line. Denial 1 1,924 Sep-20-2020, 03:38 PM
Last Post: deanhystad
  Argparse error when inputting values tqader 2 2,821 Sep-11-2020, 07:42 PM
Last Post: buran
  Why this pycharm warning for argparse formatter_class value? pjfarley3 2 2,075 Sep-09-2020, 05:23 AM
Last Post: pjfarley3
  Can argparse support undocumented options? pjfarley3 3 2,115 Aug-14-2020, 06:13 AM
Last Post: pjfarley3
  In ArgParse, can two compatible formatter_class values be used? pjfarley3 2 2,518 Jul-31-2020, 02:01 PM
Last Post: pjfarley3
  Why am I getting KeyError 'file' when using argparse? Mike Ru 1 3,027 Jun-09-2019, 04:48 PM
Last Post: metulburr
  How can I get some arguments using argparse? Mike Ru 0 1,841 Jun-05-2019, 12:57 PM
Last Post: Mike Ru
  argparse 2skywalkers 4 3,053 May-15-2019, 07:00 PM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020