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
Deprecated since version 3.2: The optparse module is deprecated and will not be developed further; development will continue with the argparse module.
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.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With