Reputation: 5098
I need to create an "interface" to my script such that (runs by crontab):
e.g. (something like the following)
python feedAnimals.py --help
...... Choices:
dog
cat
fish
python feedAnimals.py --pets dog,cat,fish
Is there anyway to do this with type="choices"
?
Or can I use type="string"
? I tried to insert \n
between choices under the "help" option, but these seems to be neglected at run time.
Must be python 2.4 compatible :(
Upvotes: 1
Views: 1559
Reputation: 294
Look this related questions, the first with a good "type='choice'" example, and the second with multiple values:
Set a default choice for optionparser when the option is given
Processing multiple values for one single option using getopt/optparse?
You may use something like this or process the arguments "by hand":
from optparse import OptionParser
def get_args():
usage = "Usage: %prog [options]"
parser = OptionParser()
parser.add_option("--pet",
type = "choice",
action = 'append',
choices = ["dog", "cat", "fish"],
default = [],
dest = pets,
help = "Available pets: [dog, cat, fish]"
)
(options, args) = parser.parse_args()
print options, args
return (options, args)
(opt, args) = get_args()
print opt.pets
Then, run:
python test.py --pet cat --pet dog --pet fish
Upvotes: 1
Reputation: 3736
This is example of how to change usage
value. Try it:
from optparse import OptionParser
string = "Choices:\n\tdog\n\tcat\n\tfish"
parser = OptionParser(usage=string)
(options,args) = parser.parse_args()
You can also change your string
to this style:
string = """
Choices:
dog
cat
fish
"""
Then test it:
$python code.py --help
In will show you this something like this result:
Usage:
Choices:
dog
cat
fish
Options:
-h, --help show this help message and exit
Upvotes: 1
Reputation: 1244
Try looking at the documentation for argparse, should do what you need - and help (-h, --help) is built in by default
https://docs.python.org/2/library/argparse.html
Upvotes: 1