Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to argparse have argument print a string and do nothing else

Tags:

python

I want to have an argument --foobar using Python argparse, so that whenever this argument appears, the program prints a particular string and exits. I don't want to consume any other arguments, I don't want to check other arguments, nothing.

I have to call add_argument somehow, and then perhaps, from parse_args() get some information and based on that, print my string.

But even though I successfully used argparse before, I am surprised to find I have trouble with this one.

For example, none of the nargs values seem to do what I want, and none of the action values seem to fit. They mess up with the other arguments, which I want to ignore once this one is seen.

How to do it?

like image 362
Mark Galeck Avatar asked Nov 23 '25 06:11

Mark Galeck


1 Answers

Use a custom action= parameter:

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

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

EDIT:

It looks like there is already an action= that does exactly what FoobarAction does. action='version' is the way to go:

import argparse

p = argparse.ArgumentParser()
p.add_argument('--foobar',
               action='version',
               version='Goodbye!',
               help='Abort!')
args = p.parse_args()
print args
like image 196
Robᵩ Avatar answered Nov 25 '25 18:11

Robᵩ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!