How to argue an argument, print a string and do nothing

I want to have an argument --foobar

using Python argparse

, so that whenever that argument appears, the program prints a specific line and exits. I don’t want to use any other arguments, I don’t want to test other arguments, nothing.

I need to call somehow add_argument

and then maybe from parse_args()

get some information and based on that print my string.

But, although I have used it successfully argparse

before, I was surprised to find that I have problems with it.

For example, none of the values nargs

seem to do what I want, and none of the values action

seem to work. They messed up other arguments that I want to ignore as soon as it can be seen.

How to do it?

+3


source to share


3 answers


Use a configurable parameter action=

:

import argparse

class FoobarAction(argparse.Action):
  def __init__(self, option_strings, dest, **kw):
    self.message = kw.pop('message', 'Goodbye!')
    argparse.Action.__init__(self, option_strings, dest, **kw)
    self.nargs = 0
  def __call__(self, parser, *args, **kw):
    print self.message
    parser.exit()

p = argparse.ArgumentParser()
p.add_argument('--ip', nargs=1, help='IP Address')
p.add_argument('--foobar',
               action=FoobarAction,
               help='Abort!')
p.add_argument('--version',
               action=FoobarAction,
               help='print the version number and exit!',
               message='1.2.3')

args = p.parse_args()
print args

      

Link: https://docs.python.org/2.7/library/argparse.html#action-classes



EDIT:

It looks like there is already one action=

that does exactly what it does FoobarAction

. action='version'

- way:

import argparse

p = argparse.ArgumentParser()
p.add_argument('--foobar',
               action='version',
               version='Goodbye!',
               help='Abort!')
args = p.parse_args()
print args

      

+1


source


I'm going to post it here, if it helps then great!

import argparse

parser = argparse.ArgumentParser(description='')
parser.add_argument('-foobar', '--foobar', help='Description for foobar argument',
                required=False)
args = vars(parser.parse_args())

if args['foobar'] == 'yes':
    foobar()

      



Using:

python myscrip.py -foobar yes

      

0


source


Use action='store_true'

( see docs ).

arg_test.py:

import argparse
import sys

p = argparse.ArgumentParser()
p.add_argument('--foobar', action='store_true')
args = p.parse_args()

if args.foobar:
    print "foobar"
    sys.exit()

      

Application:

python arg_test.py --foobar

      

Result:

foobar

      

0


source







All Articles