views:

33

answers:

2

This might be a simple one. Assume I have a program that uses argparse to process command line arguments/options. The following will print the 'help' message:

./myprogram -h

or:

./myprogram --help

But, if I run the script without any arguments whatsoever, it doesn't do anything. What I want it to do is to display the usage message when it is called with no arguments. How is that done?

A: 

you can use optparse


from optparse import OptionParser, make_option
parser = OptionParser()


parser.add_option('--var',
            help='put the help of the commandline argument')



(options, args) = parser.parse_args()

./myprogram --help

will print all the help messages for each given argument.


mossplix
+4  A: 

This answer comes from Steven Bethard on Google groups. I'm reposting it here to make it easier for people without a Google account to access.

You can override the default behavior of the error method:

import argparse
import sys

class MyParser(argparse.ArgumentParser):
    def error(self, message):
        sys.stderr.write('error: %s\n' % message)
        self.print_help()
        sys.exit(2)

parser=MyParser()
parser.add_argument('foo', nargs='+')
args=parser.parse_args()

Note that the above solution will print the help message whenever the error method is triggered. For example, test.py --blah will print the help message too if --blah isn't a valid option.

If you want to print the help message only if no arguments are supplied on the command line, then perhaps this is still the easiest way:

import argparse
import sys

parser=argparse.ArgumentParser()
parser.add_argument('foo', nargs='+')
if len(sys.argv)==1:
    parser.print_help()
    sys.exit(1)
args=parser.parse_args()
unutbu
Yeah.. that's what I was wondering about, whether there was a way for argparse to handle this scenario. Thanks!
musashiXXX