How to move optparse from main to function?
Jason Drew
jasondrew72 at gmail.com
Thu Feb 23 14:55:01 EST 2006
As pointed out, the module documentation is helpful.
For your 'test' option, I don't think 'action="count"' is the best
action. 'Test' is basically an on/off option, so why count it? I would
use:
parser.add_option("-t", "--test", action="store_true",
dest="optparse_test", default=False, help="testing optparse")
Then your code can use
if options.optparse_test == True: ...
or briefer:
if options.optparse_test: ...
As for putting the optparse code into a function, I sometimes use:
def parserSetup():
"""Return a configured option parser for this program."""
parser = OptionParser()
parser.add_option( ... your option stuff ... )
parser.add_option( ... )
return parser
if __name__=="__main__":
parser = parserSetup()
(options, args) = parser.parse_args()
# Then in your case:
if options.optparse_test: ...
More information about the Python-list
mailing list