Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optparser-print Usage Help when no argument is given

Tags:

python

What I am doing now is to simply check for args length, if it is 0, tell user to type -h.

Is there a better way to do this ? Thanks

like image 270
thinkanotherone Avatar asked Nov 15 '11 00:11

thinkanotherone


People also ask

Is Optparse deprecated?

Deprecated since version 3.2: The optparse module is deprecated and will not be developed further; development will continue with the argparse module.

What is import Optparse in Python?

Optparse module makes easy to write command-line tools. It allows argument parsing in the python program. optparse make it easy to handle the command-line argument. It comes default with python. It allows dynamic data input to change the output.


2 Answers

You can do it with optparse just fine. You don't need to use argparse.

if options.foo is None: # where foo is obviously your required option
    parser.print_help()
    sys.exit(1)
like image 101
forkchop Avatar answered Nov 13 '22 08:11

forkchop


It's not clear from your question whether you are using the (deprecated) optparse module or its replacement, the argparse module. Assuming the latter, then as long as you have at least one positional argument your script will print out a usage message if no arguments (or insufficient arguments) are supplied.

Here's an example script:

import argparse

parser = argparse.ArgumentParser(description="A dummy program")
parser.add_argument('positional', nargs="+", help="A positional argument")
parser.add_argument('--optional', help="An optional argument")

args = parser.parse_args()

If I run this with no arguments, I get this result:

usage: script.py [-h] [--optional OPTIONAL] positional [positional ...]
script.py: error: too few arguments
like image 35
srgerg Avatar answered Nov 13 '22 07:11

srgerg