Movatterモバイル変換


[0]ホーム

URL:


Up one LevelPython Library ReferenceContentsModule IndexIndex


14.3.2.5 Default values

All of the above examples involve setting some variable (the``destination'') when certain command-line options are seen. What happensif those options are never seen? Since we didn't supply any defaults,they are all set toNone. This is usually fine, but sometimes youwant more control.optparse lets you supply a default value for eachdestination, which is assigned before the command line is parsed.

First, consider the verbose/quiet example. If we wantoptparse to setverbose toTrue unless"-q" is seen, then we can do this:

parser.add_option("-v", action="store_true", dest="verbose", default=True)parser.add_option("-q", action="store_false", dest="verbose")

Since default values apply to thedestination rather than to anyparticular option, and these two options happen to have the samedestination, this is exactly equivalent:

parser.add_option("-v", action="store_true", dest="verbose")parser.add_option("-q", action="store_false", dest="verbose", default=True)

Consider this:

parser.add_option("-v", action="store_true", dest="verbose", default=False)parser.add_option("-q", action="store_false", dest="verbose", default=True)

Again, the default value forverbose will beTrue: the lastdefault value supplied for any particular destination is the one thatcounts.

A clearer way to specify default values is theset_defaults()method of OptionParser, which you can call at any time before callingparse_args():

parser.set_defaults(verbose=True)parser.add_option(...)(options, args) = parser.parse_args()

As before, the last value specified for a given option destination isthe one that counts. For clarity, try to use one method or the other ofsetting default values, not both.


Up one LevelPython Library ReferenceContentsModule IndexIndex

Release 2.5.2, documentation updated on 21st February, 2008.
SeeAbout this document... for information on suggesting changes.
[8]ページ先頭

©2009-2025 Movatter.jp