Movatterモバイル変換


[0]ホーム

URL:


Up one LevelPython Library ReferenceContentsModule IndexIndex


14.3.2 Tutorial

Whileoptparse is quite flexible and powerful, it's also straightforward touse in most cases. This section covers the code patterns that arecommon to anyoptparse-based program.

First, you need to import the OptionParser class; then, early in themain program, create an OptionParser instance:

from optparse import OptionParser[...]parser = OptionParser()

Then you can start defining options. The basic syntax is:

parser.add_option(opt_str, ...,                  attr=value, ...)

Each option has one or more option strings, such as-f or--file, and several option attributes that telloptparse what toexpect and what to do when it encounters that option on the commandline.

Typically, each option will have one short option string and one longoption string, e.g.:

parser.add_option("-f", "--file", ...)

You're free to define as many short option strings and as many longoption strings as you like (including zero), as long as there is atleast one option string overall.

The option strings passed toadd_option() are effectively labels forthe option defined by that call. For brevity, we will frequently refertoencountering an option on the command line; in reality,optparseencountersoption strings and looks up options from them.

Once all of your options are defined, instructoptparse to parse yourprogram's command line:

(options, args) = parser.parse_args()

(If you like, you can pass a custom argument list toparse_args(),but that's rarely necessary: by default it usessys.argv[1:].)

parse_args() returns two values:

This tutorial section only covers the four most important optionattributes:action,type,dest (destination), andhelp.Of these,action is the most fundamental.



Subsections


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