optparse --- Parser for command line options¶
ソースコード: Lib/optparse.py
Choosing an argument parsing library¶
The standard library includes three argument parsing libraries:
getopt: a module that closely mirrors the procedural CgetoptAPI. Included in the standard library since before the initial Python 1.0 release.optparse: a declarative replacement forgetoptthat provides equivalent functionality without requiring each application to implement its own procedural option parsing logic. Included in the standard library since the Python 2.3 release.argparse: a more opinionated alternative tooptparsethat provides more functionality by default, at the expense of reduced application flexibility in controlling exactly how arguments are processed. Included in the standard library since the Python 2.7 and Python 3.2 releases.
In the absence of more specific argument parsing design constraints, argparse
is the recommended choice for implementing command line applications, as it offers
the highest level of baseline functionality with the least application level code.
getopt is retained almost entirely for backwards compatibility reasons.
However, it also serves a niche use case as a tool for prototyping and testing
command line argument handling in getopt-based C applications.
optparse should be considered as an alternative to argparse in the
following cases:
an application is already using
optparseand doesn't want to risk the subtle behavioural changes that may arise when migrating toargparsethe application requires additional control over the way options and positional parameters are interleaved on the command line (including the ability to disable the interleaving feature completely)
the application requires additional control over the incremental parsing of command line elements (while
argparsedoes support this, the exact way it works in practice is undesirable for some use cases)the application requires additional control over the handling of options which accept parameter values that may start with
-(such as delegated options to be passed to invoked subprocesses)the application requires some other command line parameter processing behavior which
argparsedoes not support, but which can be implemented in terms of the lower level interface offered byoptparse
These considerations also mean that optparse is likely to provide a
better foundation for library authors writing third party command line
argument processing libraries.
As a concrete example, consider the following two command line argument
parsing configurations, the first using optparse, and the second
using argparse:
import optparse
if __name__ == '__main__':
parser = optparse.OptionParser()
parser.add_option('-o', '--output')
parser.add_option('-v', dest='verbose', action='store_true')
opts, args = parser.parse_args()
process(args, output=opts.output, verbose=opts.verbose)
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--output')
parser.add_argument('-v', dest='verbose', action='store_true')
parser.add_argument('rest', nargs='*')
args = parser.parse_args()
process(args.rest, output=args.output, verbose=args.verbose)
The most obvious difference is that in the optparse version, the non-option
arguments are processed separately by the application after the option processing
is complete. In the argparse version, positional arguments are declared and
processed in the same way as the named options.
However, the argparse version will also handle some parameter combination
differently from the way the optparse version would handle them.
For example (amongst other differences):
supplying
-o -vgivesoutput="-v"andverbose=Falsewhen usingoptparse, but a usage error withargparse(complaining that no value has been supplied for-o/--output, since-vis interpreted as meaning the verbosity flag)similarly, supplying
-o --givesoutput="--"andargs=()when usingoptparse, but a usage error withargparse(also complaining that no value has been supplied for-o/--output, since--is interpreted as terminating the option processing and treating all remaining values as positional arguments)supplying
-o=foogivesoutput="=foo"when usingoptparse, but givesoutput="foo"withargparse(since=is special cased as an alternative separator for option parameter values)
Whether these differing behaviors in the argparse version are
considered desirable or a problem will depend on the specific command line
application use case.
参考
click is a third party argument processing library (originally
based on optparse), which allows command line applications to be
developed as a set of decorated command implementation functions.
Other third party libraries, such as typer or msgspec-click, allow command line interfaces to be specified in ways that more effectively integrate with static checking of Python type annotations.
はじめに¶
optparse is a more convenient, flexible, and powerful library for parsing
command-line options than the minimalist getopt module.
optparse uses a more declarative style of command-line parsing:
you create an instance of OptionParser,
populate it with options, and parse the command line.
optparse allows users to specify options in the conventional
GNU/POSIX syntax, and additionally generates usage and help messages for you.
Here's an example of using optparse in a simple script:
from optparse import OptionParser
...
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't print status messages to stdout")
(options, args) = parser.parse_args()
このようにわずかな行数のコードによって、スクリプトのユーザはコマンドライン上で例えば以下のような「よくある使い方」を実行できるようになります:
<yourscript> --file=outfile -q
As it parses the command line, optparse sets attributes of the
options object returned by parse_args() based on user-supplied
command-line values. When parse_args() returns from parsing this command
line, options.filename will be "outfile" and options.verbose will be
False. optparse supports both long and short options, allows short
options to be merged together, and allows options to be associated with their
arguments in a variety of ways. Thus, the following command lines are all
equivalent to the above example:
<yourscript> -f outfile --quiet
<yourscript> --quiet --file outfile
<yourscript> -q -foutfile
<yourscript> -qfoutfile
さらに、ユーザが以下のいずれかを実行すると
<yourscript> -h
<yourscript> --help
and optparse will print out a brief summary of your script's options:
Usage: <yourscript> [options]
Options:
-h, --help show this help message and exit
-f FILE, --file=FILE write report to FILE
-q, --quiet don't print status messages to stdout
yourscript の中身は実行時に決まります (通常は sys.argv[0] になります)。
背景¶
optparse was explicitly designed to encourage the creation of programs
with straightforward command-line interfaces that follow the conventions
established by the getopt() family of functions available to C developers.
To that end, it supports only the most common command-line syntax and semantics
conventionally used under Unix. If you are unfamiliar with these conventions,
reading this section will allow you to acquaint yourself with them.
用語集¶
- 引数 (argument)
コマンドラインでユーザが入力するテキストの塊で、シェルが
execlやexecvに引き渡すものです。Python では、引数はsys.argv[1:]の要素となります。(sys.argv[0]は実行しようとしているプログラムの名前です。引数解析に関しては、この要素はあまり重要ではありません。) Unix シェルでは、「語 (word)」という用語も使います。場合によっては
sys.argv[1:]以外の引数リストを代入する方が望ましいことがあるので、「引数」は「sys.argv[1:]またはsys.argv[1:]の代替として提供される別のリストの要素」と読むべきでしょう。- オプション (option)
an argument used to supply extra information to guide or customize the execution of a program. There are many different syntaxes for options; the traditional Unix syntax is a hyphen ("-") followed by a single letter, e.g.
-xor-F. Also, traditional Unix syntax allows multiple options to be merged into a single argument, e.g.-x -Fis equivalent to-xF. The GNU project introduced--followed by a series of hyphen-separated words, e.g.--fileor--dry-run. These are the only two option syntaxes provided byoptparse.他に見られる他のオプション書法には以下のようなものがあります:
ハイフンの後ろに数個の文字が続くもので、例えば
-pf(このオプションは複数のオプションを一つにまとめたものとは 違います)ハイフンの後ろに語が続くもので、例えば
-file(これは技術的には上の書式と同じですが、通常同じプログラム上で一緒に使うことはありません)プラス記号の後ろに一文字、数個の文字、または語を続けたもので、例えば
+f,+rgbスラッシュ記号の後ろに一文字、数個の文字、または語を続けたもので、例えば
/f,/file
These option syntaxes are not supported by
optparse, and they never will be. This is deliberate: the first three are non-standard on any environment, and the last only makes sense if you're exclusively targeting Windows or certain legacy platforms (e.g. VMS, MS-DOS).- オプション引数 (option argument)
an argument that follows an option, is closely associated with that option, and is consumed from the argument list when that option is. With
optparse, option arguments may either be in a separate argument from their option:-f foo --file foo
また、一つの引数中にも入れられます:
-ffoo --file=foo
Typically, a given option either takes an argument or it doesn't. Lots of people want an "optional option arguments" feature, meaning that some options will take an argument if they see it, and won't if they don't. This is somewhat controversial, because it makes parsing ambiguous: if
-atakes an optional argument and-bis another option entirely, how do we interpret-ab? Because of this ambiguity,optparsedoes not support this feature.- 位置引数 (positional argument)
他のオプションが解析される、すなわち他のオプションとその引数が解析されて引数リストから除去された後に引数リストに置かれているものです。
- 必須のオプション (required option)
an option that must be supplied on the command-line; note that the phrase "required option" is self-contradictory in English.
optparsedoesn't prevent you from implementing required options, but doesn't give you much help at it either.
例えば、下記のような架空のコマンドラインを考えてみましょう:
prog -v --report report.txt foo bar
-v と --report はどちらもオプションです。--report オプションが引数をとるとすれば、report.txt はオプションの引数です。foo と bar は位置引数になります。
オプションとは何か¶
オプションはプログラムの実行を調整したり、カスタマイズしたりするための補助的な情報を与えるために使います。もっとはっきりいうと、オプションはあくまでもオプション (省略可能)であるということです。本来、プログラムはともかくもオプションなしでうまく実行できてしかるべきです。(Unix やGNU ツールセットのプログラムをランダムにピックアップしてみてください。オプションを全く指定しなくてもちゃんと動くでしょう?例外は find, tar, dd くらいです---これらの例外は、オプション文法が標準的でなく、インターフェースが混乱を招くと酷評されてきた変種のはみ出しものなのです)
多くの人が自分のプログラムに「必須のオプション」を持たせたいと考えます。しかしよく考えてください。必須なら、それは オプション(省略可能) ではないのです! プログラムを正しく動作させるのに絶対的に必要な情報があるとすれば、そこには位置引数を割り当てるべきなのです。
良くできたコマンドライン インターフェース設計として、ファイルのコピーに使われる cp ユーティリティのことを考えてみましょう。ファイルのコピーでは、コピー先を指定せずにファイルをコピーするのは無意味な操作ですし、少なくとも一つのコピー元が必要です。従って、cp は引数無しで実行すると失敗します。とはいえ、cp はオプションを全く必要としない柔軟で便利なコマンドライン文法を備えています:
cp SOURCE DEST
cp SOURCE ... DEST-DIR
まだあります。ほとんどの cp の実装では、ファイルモードや変更時刻を変えずにコピーする、シンボリックリンクの追跡を行わない、すでにあるファイルを上書きする前にユーザに尋ねる、など、ファイルをコピーする方法をいじるための一連のオプションを実装しています。しかし、こうしたオプションは、一つのファイルを別の場所にコピーする、または複数のファイルを別のディレクトリにコピーするという、cp の中心的な処理を乱すことはないのです。
位置引数とは何か¶
位置引数とは、プログラムを動作させる上で絶対的に必要な情報となる引数です。
よいユーザインターフェースとは、絶対に必要だとされるものが可能な限り少ないものです。プログラムを正しく動作させるために 17 個もの別個の情報が必要だとしたら、その 方法 はさして問題にはなりません ---ユーザはプログラムを正しく動作させられないうちに諦め、立ち去ってしまうからです。ユーザインターフェースがコマンドラインでも、設定ファイルでも、GUI やその他の何であっても同じです: 多くの要求をユーザに押し付ければ、ほとんどのユーザはただ音をあげてしまうだけなのです。
要するに、ユーザが絶対に提供しなければならない情報だけに制限する --- そして可能な限りよく練られたデフォルト設定を使うよう試みてください。もちろん、プログラムには適度な柔軟性を持たせたいとも望むはずですが、それこそがオプションの果たす役割です。繰り返しますが、設定ファイルのエントリであろうが、GUI でできた「環境設定」ダイアログ上のウィジェットであろうが、コマンドラインオプションであろうが関係ありません --- より多くのオプションを実装すればプログラムはより柔軟性を持ちますが、実装はより難解になるのです。高すぎる柔軟性はユーザを閉口させ、コードの維持をより難しくするのです。
チュートリアル¶
While optparse is quite flexible and powerful, it's also straightforward
to use in most cases. This section covers the code patterns that are common to
any optparse-based program.
まず、OptionParser クラスを import しておかなければなりません。次に、プログラムの冒頭で OptionParser インスタンスを生成しておきます:
from optparse import OptionParser
...
parser = OptionParser()
これでオプションを定義できるようになりました。基本的な構文は以下の通りです:
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 tell optparse what to expect and what
to do when it encounters that option on the command line.
通常、各オプションには短いオプション文字列と長いオプション文字列があります。例えば:
parser.add_option("-f", "--file", ...)
オプション文字列は、(ゼロ文字の場合も含め)いくらでも短く、またいくらでも長くできます。ただしオプション文字列は少なくとも一つなければなりません。
The option strings passed to OptionParser.add_option() are effectively
labels for the
option defined by that call. For brevity, we will frequently refer to
encountering an option on the command line; in reality, optparse
encounters option strings and looks up options from them.
Once all of your options are defined, instruct optparse to parse your
program's command line:
(options, args) = parser.parse_args()
(お望みなら、 parse_args() に自作の引数リストを渡してもかまいません。とはいえ、実際にはそうした必要はほとんどないでしょう: optionparser はデフォルトで sys.argv[1:] を使うからです。)
parse_args() は二つの値を返します:
全てのオプションに対する値の入ったオブジェクト
options--- 例えば、--fileが単一の文字列引数をとる場合、options.fileはユーザが指定したファイル名になります。オプションを指定しなかった場合にはNoneになりますオプションの解析後に残った位置引数からなるリスト
args
このチュートリアルの節では、最も重要な四つのオプション属性: action, type, dest (destination), help についてしか触れません。このうち最も重要なのは action です。
オプション・アクションを理解する¶
Actions tell optparse what to do when it encounters an option on the
command line. There is a fixed set of actions hard-coded into optparse;
adding new actions is an advanced topic covered in section
Extending optparse. Most actions tell optparse to store
a value in some variable---for example, take a string from the command line and
store it in an attribute of options.
If you don't specify an option action, optparse defaults to store.
store アクション¶
The most common option action is store, which tells optparse to take
the next argument (or the remainder of the current argument), ensure that it is
of the correct type, and store it to your chosen destination.
例えば:
parser.add_option("-f", "--file",
action="store", type="string", dest="filename")
Now let's make up a fake command line and ask optparse to parse it:
args = ["-f", "foo.txt"]
(options, args) = parser.parse_args(args)
When optparse sees the option string -f, it consumes the next
argument, foo.txt, and stores it in options.filename. So, after this
call to parse_args(), options.filename is "foo.txt".
Some other option types supported by optparse are int and float.
Here's an option that expects an integer argument:
parser.add_option("-n", type="int", dest="num")
このオプションには長い形式のオプション文字列がないため、設定に問題がないということに注意してください。また、デフォルトのアクションは store なので、ここでは action を明示的に指定していません。
架空のコマンドラインをもう一つ解析してみましょう。今度は、オプション引数をオプションの右側にぴったりくっつけて一緒くたにします: -n42 (一つの引数のみ) は -n 42 (二つの引数からなる) と等価になるので
(options, args) = parser.parse_args(["-n42"])
print(options.num)
は 42 を出力します。
If you don't specify a type, optparse assumes string. Combined with
the fact that the default action is store, that means our first example can
be a lot shorter:
parser.add_option("-f", "--file", dest="filename")
If you don't supply a destination, optparse figures out a sensible
default from the option strings: if the first long option string is
--foo-bar, then the default destination is foo_bar. If there are no
long option strings, optparse looks at the first short option string: the
default destination for -f is f.
optparse also includes the built-in complex type. Adding
types is covered in section Extending optparse.
ブール値 (フラグ) オプションの処理¶
Flag options---set a variable to true or false when a particular option is
seen---are quite common. optparse supports them with two separate actions,
store_true and store_false. For example, you might have a verbose
flag that is turned on with -v and off with -q:
parser.add_option("-v", action="store_true", dest="verbose")
parser.add_option("-q", action="store_false", dest="verbose")
ここでは二つのオプションに同じ保存先を指定していますが、全く問題ありません。(下記のように、デフォルト値の設定を少し注意深く行わなければならないだけです。)
When optparse encounters -v on the command line, it sets
options.verbose to True; when it encounters -q,
options.verbose is set to False.
その他のアクション¶
Some other actions supported by optparse are:
"store_const"store a constant value, pre-set via
Option.const"append"オプションの引数を指定のリストに追加します
"count"指定のカウンタを 1 増やします
"callback"指定の関数を呼び出します
これらのアクションについては、 リファレンスガイド 節および オプション処理コールバック 節で触れます。
デフォルト値¶
All of the above examples involve setting some variable (the "destination") when
certain command-line options are seen. What happens if those options are never
seen? Since we didn't supply any defaults, they are all set to None. This
is usually fine, but sometimes you want more control. optparse lets you
supply a default value for each destination, which is assigned before the
command line is parsed.
First, consider the verbose/quiet example. If we want optparse to set
verbose to True 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")
デフォルトの値は特定のオプションではなく 保存先 に対して適用されます。また、これら二つのオプションはたまたま同じ保存先を持っているにすぎないため、上のコードは下のコードと全く等価になります:
parser.add_option("-v", action="store_true", dest="verbose")
parser.add_option("-q", action="store_false", dest="verbose", default=True)
下のような場合を考えてみましょう:
parser.add_option("-v", action="store_true", dest="verbose", default=False)
parser.add_option("-q", action="store_false", dest="verbose", default=True)
やはり verbose のデフォルト値は True になります; 特定の目的変数に対するデフォルト値として有効なのは、最後に指定した値だからです。
デフォルト値をすっきりと指定するには、 OptionParser の set_defaults() メソッドを使います。このメソッドは parse_args() を呼び出す前ならいつでも使えます:
parser.set_defaults(verbose=True)
parser.add_option(...)
(options, args) = parser.parse_args()
前の例と同様、あるオプションの値の保存先に対するデフォルトの値は最後に指定した値になります。コードを読みやすくするため、デフォルト値を設定するときには両方のやり方を混ぜるのではなく、片方だけを使うようにしましょう。
ヘルプの生成¶
optparse's ability to generate help and usage text automatically is
useful for creating user-friendly command-line interfaces. All you have to do
is supply a help value for each option, and optionally a short
usage message for your whole program. Here's an OptionParser populated with
user-friendly (documented) options:
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose", default=True,
help="make lots of noise [default]")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose",
help="be vewwy quiet (I'm hunting wabbits)")
parser.add_option("-f", "--filename",
metavar="FILE", help="write output to FILE")
parser.add_option("-m", "--mode",
default="intermediate",
help="interaction mode: novice, intermediate, "
"or expert [default: %default]")
If optparse encounters either -h or --help on the
command-line, or if you just call parser.print_help(), it prints the
following to standard output:
Usage: <yourscript> [options] arg1 arg2
Options:
-h, --help show this help message and exit
-v, --verbose make lots of noise [default]
-q, --quiet be vewwy quiet (I'm hunting wabbits)
-f FILE, --filename=FILE
write output to FILE
-m MODE, --mode=MODE interaction mode: novice, intermediate, or
expert [default: intermediate]
(If the help output is triggered by a help option, optparse exits after
printing the help text.)
There's a lot going on here to help optparse generate the best possible
help message:
スクリプト自体の利用法を表すメッセージを定義します:
usage = "usage: %prog [options] arg1 arg2"
optparseexpands%progin the usage string to the name of the current program, i.e.os.path.basename(sys.argv[0]). The expanded string is then printed before the detailed option help.If you don't supply a usage string,
optparseuses a bland but sensible default:"Usage: %prog [options]", which is fine if your script doesn't take any positional arguments.every option defines a help string, and doesn't worry about line-wrapping---
optparsetakes care of wrapping lines and making the help output look good.オプションが値をとるということは自動的に生成されるヘルプメッセージの中で分かります。例えば、"mode" option の場合にはこのようになります:
-m MODE, --mode=MODE
Here, "MODE" is called the meta-variable: it stands for the argument that the user is expected to supply to
-m/--mode. By default,optparseconverts the destination variable name to uppercase and uses that for the meta-variable. Sometimes, that's not what you want---for example, the--filenameoption explicitly setsmetavar="FILE", resulting in this automatically generated option description:-f FILE, --filename=FILE
この機能の重要さは、単に表示スペースを節約するといった理由にとどまりません: 上の例では、手作業で書いたヘルプテキストの中でメタ変数として
FILEを使っています。その結果、ユーザに対してやや堅苦しい表現の書法-f FILEと、より平易に意味付けを説明した "write output to FILE" との間に対応があるというヒントを与えています。これは、エンドユーザにとってより明解で便利なヘルプテキストを作成する単純でありながら効果的な手法なのです。options that have a default value can include
%defaultin the help string---optparsewill replace it withstr()of the option's default value. If an option has no default value (or the default value isNone),%defaultexpands tonone.
オプションをグループ化する¶
たくさんのオプションを扱う場合、オプションをグループ分けするとヘルプ出力が見やすくなります。 OptionParser は、複数のオプションをまとめたオプショングループを複数持つことができます。
オプションのグループは、 OptionGroup を使って作成します:
- class optparse.OptionGroup(parser, title, description=None)¶
ここでは:
parser は、このグループが属する
OptionParserのインスタンスですtitle はグループのタイトルです
description はオプションで、グループの長い説明です
OptionGroup は (OptionParser のように) OptionContainer を継承していて、オプションをグループに追加するために add_option() メソッドを利用できます。
全てのオプションを定義したら、 OptionParser の add_option_group() メソッドを使ってグループを定義済みのパーサーに追加します。
前のセクションで定義したパーサーに、続けて OptionGroup を追加します:
group = OptionGroup(parser, "Dangerous Options",
"Caution: use these options at your own risk. "
"It is believed that some of them bite.")
group.add_option("-g", action="store_true", help="Group option.")
parser.add_option_group(group)
この結果のヘルプ出力は次のようになります:
Usage: <yourscript> [options] arg1 arg2
Options:
-h, --help show this help message and exit
-v, --verbose make lots of noise [default]
-q, --quiet be vewwy quiet (I'm hunting wabbits)
-f FILE, --filename=FILE
write output to FILE
-m MODE, --mode=MODE interaction mode: novice, intermediate, or
expert [default: intermediate]
Dangerous Options:
Caution: use these options at your own risk. It is believed that some
of them bite.
-g Group option.
さらにサンプルを拡張して、複数のグループを使うようにしてみます:
group = OptionGroup(parser, "Dangerous Options",
"Caution: use these options at your own risk. "
"It is believed that some of them bite.")
group.add_option("-g", action="store_true", help="Group option.")
parser.add_option_group(group)
group = OptionGroup(parser, "Debug Options")
group.add_option("-d", "--debug", action="store_true",
help="Print debug information")
group.add_option("-s", "--sql", action="store_true",
help="Print all SQL statements executed")
group.add_option("-e", action="store_true", help="Print every action done")
parser.add_option_group(group)
出力結果は次のようになります:
Usage: <yourscript> [options] arg1 arg2
Options:
-h, --help show this help message and exit
-v, --verbose make lots of noise [default]
-q, --quiet be vewwy quiet (I'm hunting wabbits)
-f FILE, --filename=FILE
write output to FILE
-m MODE, --mode=MODE interaction mode: novice, intermediate, or expert
[default: intermediate]
Dangerous Options:
Caution: use these options at your own risk. It is believed that some
of them bite.
-g Group option.
Debug Options:
-d, --debug Print debug information
-s, --sql Print all SQL statements executed
-e Print every action done
もう1つの、特にオプショングループをプログラムから操作するときに利用できるメソッドがあります:
- OptionParser.get_option_group(opt_str)¶
短いオプション文字列もしくは長いオプション文字列 opt_str (例。
'-o'、'--option') が属するOptionGroupを返します。そのようなOptionGroupが無い場合は、Noneを返します。
バージョン番号の出力¶
Similar to the brief usage string, optparse can also print a version
string for your program. You have to supply the string as the version
argument to OptionParser:
parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
%prog is expanded just like it is in usage. Apart from that,
version can contain anything you like. When you supply it, optparse
automatically adds a --version option to your parser. If it encounters
this option on the command line, it expands your version string (by
replacing %prog), prints it to stdout, and exits.
例えば、/usr/bin/foo という名前のスクリプトなら:
$ /usr/bin/foo --version
foo 1.0
以下の2つのメソッドを、version 文字列を表示するために利用できます:
- OptionParser.print_version(file=None)¶
現在のプログラムのバージョン (
self.version) を file (デフォルト: stdout) へ表示します。print_usage()と同じく、self.versionの中の全ての%progが現在のプログラム名に置き換えられます。self.versionが空文字列だだったり未定義だったときは何もしません。
- OptionParser.get_version()¶
print_version()と同じですが、バージョン文字列を表示する代わりに返します。
How optparse handles errors¶
There are two broad classes of errors that optparse has to worry about:
programmer errors and user errors. Programmer errors are usually erroneous
calls to OptionParser.add_option(), e.g. invalid option strings, unknown
option attributes, missing option attributes, etc. These are dealt with in the
usual way: raise an exception (either optparse.OptionError or
TypeError) and let the program crash.
Handling user errors is much more important, since they are guaranteed to happen
no matter how stable your code is. optparse can automatically detect
some user errors, such as bad option arguments (passing -n 4x where
-n takes an integer argument), missing arguments (-n at the end
of the command line, where -n takes an argument of any type). Also,
you can call OptionParser.error() to signal an application-defined error
condition:
(options, args) = parser.parse_args()
...
if options.a and options.b:
parser.error("options -a and -b are mutually exclusive")
In either case, optparse handles the error the same way: it prints the
program's usage message and an error message to standard error and exits with
error status 2.
上に挙げた最初の例、すなわち整数を引数にとるオプションにユーザが 4x を指定した場合を考えてみましょう:
$ /usr/bin/foo -n 4x
Usage: foo [options]
foo: error: option -n: invalid integer value: '4x'
値を全く指定しない場合には、以下のようになります:
$ /usr/bin/foo -n
Usage: foo [options]
foo: error: -n option requires an argument
optparse-generated error messages take care always to mention the
option involved in the error; be sure to do the same when calling
OptionParser.error() from your application code.
If optparse's default error-handling behaviour does not suit your needs,
you'll need to subclass OptionParser and override its exit()
and/or error() methods.
全てをつなぎ合わせる¶
Here's what optparse-based scripts usually look like:
from optparse import OptionParser
...
def main():
usage = "usage: %prog [options] arg"
parser = OptionParser(usage)
parser.add_option("-f", "--file", dest="filename",
help="read data from FILENAME")
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose")
...
(options, args) = parser.parse_args()
if len(args) != 1:
parser.error("incorrect number of arguments")
if options.verbose:
print("reading %s..." % options.filename)
...
if __name__ == "__main__":
main()
リファレンスガイド¶
parserを作る¶
The first step in using optparse is to create an OptionParser instance.
- class optparse.OptionParser(...)¶
OptionParser のコンストラクタの引数はどれも必須ではありませんが、いくつものキーワード引数がオプションとして使えます。これらはキーワード引数として渡さなければなりません。すなわち、引数が宣言されている順番に頼ってはいけません。
usage(デフォルト:"%prog [options]")The usage summary to print when your program is run incorrectly or with a help option. When
optparseprints the usage string, it expands%progtoos.path.basename(sys.argv[0])(or toprogif you passed that keyword argument). To suppress a usage message, pass the special valueoptparse.SUPPRESS_USAGE.option_list(デフォルト:[])パーザに追加する Option オブジェクトのリストです。
option_listの中のオプションはstandard_option_list(OptionParser のサブクラスでセットされる可能性のあるクラス属性) の後に追加されますが、バージョンやヘルプのオプションよりは前になります。このオプションの使用は推奨されません。パーザを作成した後で、add_option()を使って追加してください。option_class(デフォルト: optparse.Option)add_option()でパーザにオプションを追加するときに使用されるクラス。version(デフォルト:None)A version string to print when the user supplies a version option. If you supply a true value for
version,optparseautomatically adds a version option with the single option string--version. The substring%progis expanded the same as forusage.conflict_handler(デフォルト:"error")オプション文字列が衝突するようなオプションがパーザに追加されたときにどうするかを指定します。 オプション間の衝突 節を参照して下さい。
description(デフォルト:None)A paragraph of text giving a brief overview of your program.
optparsereformats this paragraph to fit the current terminal width and prints it when the user requests help (afterusage, but before the list of options).formatter(デフォルト: 新しいIndentedHelpFormatter)An instance of optparse.HelpFormatter that will be used for printing help text.
optparseprovides two concrete classes for this purpose: IndentedHelpFormatter and TitledHelpFormatter.add_help_option(デフォルト:True)If true,
optparsewill add a help option (with option strings-hand--help) to the parser.progusageやversionの中の%progを展開するときにos.path.basename(sys.argv[0])の代わりに使われる文字列です。epilog(デフォルト:None)オプションのヘルプの後に表示されるヘルプテキスト.
パーザへのオプション追加¶
パーザにオプションを加えていくにはいくつか方法があります。推奨するのは チュートリアル 節で示したような OptionParser.add_option() を使う方法です。 add_option() は以下の二つのうちいずれかの方法で呼び出せます:
(
make_option()などが返す)Optionインスタンスを渡しますmake_option()に (すなわちOptionのコンストラクタに) 位置引数とキーワード引数の組み合わせを渡して、Optionインスタンスを生成させます
もう一つの方法は、あらかじめ作成しておいた Option インスタンスからなるリストを、以下のようにして OptionParser のコンストラクタに渡すというものです:
option_list = [
make_option("-f", "--filename",
action="store", type="string", dest="filename"),
make_option("-q", "--quiet",
action="store_false", dest="verbose"),
]
parser = OptionParser(option_list=option_list)
(make_option() is a factory function for creating Option instances;
currently it is an alias for the Option constructor. A future version of
optparse may split Option into several classes, and make_option()
will pick the right class to instantiate. Do not instantiate Option directly.)
オプションの定義¶
各々の Option インスタンス、は -f や --file といった同義のコマンドラインオプションからなる集合を表現しています。一つの Option には任意の数のオプションを短い形式でも長い形式でも指定できます。ただし、少なくとも一つは指定しなければなりません。
正しい方法で Option インスタンスを生成するには、 OptionParser の add_option() を使います。
- OptionParser.add_option(option)¶
- OptionParser.add_option(*opt_str, attr=value, ...)
短い形式のオプション文字列を一つだけ持つようなオプションを生成するには次のようにします:
parser.add_option("-f", attr=value, ...)
また、長い形式のオプション文字列を一つだけ持つようなオプションの定義は次のようになります:
parser.add_option("--foo", attr=value, ...)
The keyword arguments define attributes of the new Option object. The most important option attribute is
action, and it largely determines which other attributes are relevant or required. If you pass irrelevant option attributes, or fail to pass required ones,optparseraises anOptionErrorexception explaining your mistake.An option's action determines what
optparsedoes when it encounters this option on the command-line. The standard option actions hard-coded intooptparseare:"store"オプションの引数を保存します (デフォルトの動作です)
"store_const"store a constant value, pre-set via
Option.const"store_true"store
True"store_false"store
False"append"オプションの引数を指定のリストに追加します
"append_const"append a constant value to a list, pre-set via
Option.const"count"指定のカウンタを 1 増やします
"callback"指定の関数を呼び出します
"help"全てのオプションとそのドキュメントの入った使用法メッセージを出力します
(アクションを指定しない場合、デフォルトは
"store"になります。このアクションでは、typeおよびdestオプション属性を指定できます。 標準的なオプション・アクション を参照してください。)
As you can see, most actions involve storing or updating a value somewhere.
optparse always creates a special object for this, conventionally called
options, which is an instance of optparse.Values.
- class optparse.Values¶
An object holding parsed argument names and values as attributes. Normally created by calling when calling
OptionParser.parse_args(), and can be overridden by a custom subclass passed to the values argument ofOptionParser.parse_args()(as described in 引数を解析する).
Option
arguments (and various other values) are stored as attributes of this object,
according to the dest (destination) option attribute.
例えばこれを呼び出した場合
parser.parse_args()
one of the first things optparse does is create the options object:
options = Values()
パーザ中で以下のようなオプションが定義されていて
parser.add_option("-f", "--file", action="store", type="string", dest="filename")
パーズしたコマンドラインに以下のいずれかが入っていた場合:
-ffoo
-f foo
--file=foo
--file foo
then optparse, on seeing this option, will do the equivalent of
options.filename = "foo"
type および dest オプション属性は action と同じくらい重要ですが、 全ての オプションで意味をなすのは action だけなのです。
オプション属性¶
- class optparse.Option¶
A single command line argument, with various attributes passed by keyword to the constructor. Normally created with
OptionParser.add_option()rather than directly, and can be overridden by a custom class via the option_class argument toOptionParser.
The following option attributes may be passed as keyword arguments to
OptionParser.add_option(). If you pass an option attribute that is not
relevant to a particular option, or fail to pass a required option attribute,
optparse raises OptionError.
- Option.action¶
(デフォルト:
"store")Determines
optparse's behaviour when this option is seen on the command line; the available options are documented here.
- Option.type¶
(デフォルト:
"string")このオプションに与えられる引数の型 (たとえば
"string"や"int") です。取りうるオプションについては こちら を参照してください。
- Option.dest¶
(デフォルト: オプション文字列を使う)
If the option's action implies writing or modifying a value somewhere, this tells
optparsewhere to write it:destnames an attribute of theoptionsobject thatoptparsebuilds as it parses the command line.
- Option.default¶
コマンドラインに指定がなかったときにこのオプションの対象に使われる値です。
OptionParser.set_defaults()も参照してください。
- Option.nargs¶
(デフォルト: 1)
How many arguments of type
typeshould be consumed when this option is seen. If > 1,optparsewill store a tuple of values todest.
- Option.const¶
定数を格納する動作のための、その定数です。
- Option.choices¶
"choice"型オプションに対してユーザが選べる選択肢となる文字列のリストです。
- Option.callback¶
アクションが
"callback"であるオプションに対し、このオプションがあったときに呼ばれる呼び出し可能オブジェクトです。呼び出し時に渡される引数の詳細については、 オプション処理コールバック を参照してください。
標準的なオプション・アクション¶
The various option actions all have slightly different requirements and effects.
Most actions have several relevant option attributes which you may specify to
guide optparse's behaviour; a few have required attributes, which you
must specify for any option using that action.
"store"[関連:type,dest,nargs,choices]オプションの後には必ず引数が続きます。引数は
typeに従って値に変換されてdestに保存されます。nargs> 1 の場合、複数の引数をコマンドラインから取り出します。引数は全てtypeに従って変換され、destにタプルとして保存されます。 標準のオプション型 節を参照してください。choicesを(文字列のリストかタプルで) 指定した場合、型のデフォルト値は"choice"になります。typeを指定しない場合、デフォルトの値は"string"です。If
destis not supplied,optparsederives a destination from the first long option string (e.g.,--foo-barimpliesfoo_bar). If there are no long option strings,optparsederives a destination from the first short option string (e.g.,-fimpliesf).以下はプログラム例です:
parser.add_option("-f") parser.add_option("-p", type="float", nargs=3, dest="point")
とすると、以下のようなコマンドライン
-f foo.txt -p 1 -3.5 4 -fbar.txt
optparsewill setoptions.f = "foo.txt" options.point = (1.0, -3.5, 4.0) options.f = "bar.txt"
"store_const"[関連:const; 関連:dest]以下はプログラム例です:
parser.add_option("-q", "--quiet", action="store_const", const=0, dest="verbose") parser.add_option("-v", "--verbose", action="store_const", const=1, dest="verbose") parser.add_option("--noisy", action="store_const", const=2, dest="verbose")
If
--noisyis seen,optparsewill setoptions.verbose = 2
"store_true"[関連:dest]A special case of
"store_const"that storesTruetodest."store_false"[関連:dest]Like
"store_true", but storesFalse.以下はプログラム例です:
parser.add_option("--clobber", action="store_true", dest="clobber") parser.add_option("--no-clobber", action="store_false", dest="clobber")
"append"[関連:type,dest,nargs,choices]The option must be followed by an argument, which is appended to the list in
dest. If no default value fordestis supplied, an empty list is automatically created whenoptparsefirst encounters this option on the command-line. Ifnargs> 1, multiple arguments are consumed, and a tuple of lengthnargsis appended todest.typeおよびdestのデフォルト値は"store"アクションと同じです。以下はプログラム例です:
parser.add_option("-t", "--tracks", action="append", type="int")
If
-t3is seen on the command-line,optparsedoes the equivalent of:options.tracks = [] options.tracks.append(int("3"))
その後、
--tracks=4が見つかると以下を実行します:options.tracks.append(int("4"))
appendアクションは、オプションの現在の値のappendメソッドを呼び出します。これは、どのデフォルト値もappendメソッドを持っていなければならないことを意味します。また、デフォルト値が空でない場合、オプションの解析結果は、そのデフォルトの要素の後ろにコマンドラインからの値が追加されたものになる、ということも意味します:>>> parser.add_option("--files", action="append", default=['~/.mypkg/defaults']) >>> opts, args = parser.parse_args(['--files', 'overrides.mypkg']) >>> opts.files ['~/.mypkg/defaults', 'overrides.mypkg']
"append_const"[関連:const; 関連:dest]"store_const"と同様ですが、constの値はdestに追加(append)されます。"append"の場合と同じようにdestのデフォルトはNoneですがこのオプションを最初にみつけた時点で空のリストを自動的に生成します。"count"[関連:dest]destに保存されている整数値をインクリメントします。destは (デフォルトの値を指定しない限り) 最初にインクリメントを行う前にゼロに設定されます。以下はプログラム例です:
parser.add_option("-v", action="count", dest="verbosity")
The first time
-vis seen on the command line,optparsedoes the equivalent of:options.verbosity = 0 options.verbosity += 1
以後、
-vが見つかるたびにoptions.verbosity += 1
"callback"[必須:callback; 関連:type,nargs,callback_args,callback_kwargs]callbackに指定された関数を次のように呼び出しますfunc(option, opt_str, value, parser, *args, **kwargs)
詳細は、 オプション処理コールバック 節を参照してください。
"help"現在のオプションパーザ内の全てのオプションに対する完全なヘルプメッセージを出力します。ヘルプメッセージは
OptionParserのコンストラクタに渡したusage文字列と、各オプションに渡したhelp文字列から生成します。オプションに
help文字列が指定されていなくても、オプションはヘルプメッセージ中に列挙されます。オプションを完全に表示させないようにするには、特殊な値optparse.SUPPRESS_HELPを使ってください。optparseautomatically adds ahelpoption to all OptionParsers, so you do not normally need to create one.以下はプログラム例です:
from optparse import OptionParser, SUPPRESS_HELP # usually, a help option is added automatically, but that can # be suppressed using the add_help_option argument parser = OptionParser(add_help_option=False) parser.add_option("-h", "--help", action="help") parser.add_option("-v", action="store_true", dest="verbose", help="Be moderately verbose") parser.add_option("--file", dest="filename", help="Input file to read data from") parser.add_option("--secret", help=SUPPRESS_HELP)
If
optparsesees either-hor--helpon the command line, it will print something like the following help message to stdout (assumingsys.argv[0]is"foo.py"):Usage: foo.py [options] Options: -h, --help Show this help message and exit -v Be moderately verbose --file=FILENAME Input file to read data from
After printing the help message,
optparseterminates your process withsys.exit(0)."version"Prints the version number supplied to the OptionParser to stdout and exits. The version number is actually formatted and printed by the
print_version()method of OptionParser. Generally only relevant if theversionargument is supplied to the OptionParser constructor. As withhelpoptions, you will rarely createversionoptions, sinceoptparseautomatically adds them when needed.
標準のオプション型¶
optparse has five built-in option types: "string", "int",
"choice", "float" and "complex". If you need to add new
option types, see section Extending optparse.
文字列オプションの引数はチェックや変換を一切受けません: コマンドライン上のテキストは保存先にそのまま保存されます (またはコールバックに渡されます)。
整数引数 ("int" 型) は次のように解析されます:
数が
0xから始まるならば、16進数として読み取られます数が
0から始まるならば、8進数として読み取られます数が
0bから始まるならば、2進数として読み取られますそれ以外の場合、数は10進数として読み取られます
The conversion is done by calling int() with the appropriate base (2, 8,
10, or 16). If this fails, so will optparse, although with a more useful
error message.
"float" および "complex" のオプション引数は直接 float() や complex() で変換されます。エラーは同様の扱いです。
"choice" オプションは "string" オプションのサブタイプです。 choices オプションの属性 (文字列からなるシーケンス) には、利用できるオプション引数のセットを指定します。 optparse.check_choice() はユーザの指定したオプション引数とマスタリストを比較して、無効な文字列が指定された場合には OptionValueError を送出します。
引数を解析する¶
OptionParser を作成してオプションを追加していく上で大事なポイントは、 parse_args() メソッドの呼び出しです。
- OptionParser.parse_args(args=None, values=None)¶
Parse the command-line options found in args.
The input parameters are
args処理する引数のリスト (デフォルト:
sys.argv[1:])valuesオプション引数を格納する
Valuesのオブジェクト (デフォルト: 新しいValuesのインスタンス) -- 既存のオブジェクトを指定した場合、オプションのデフォルトは初期化されません
and the return value is a pair
(options, args)whereoptionsthe same object that was passed in as values, or the
optparse.Valuesinstance created byoptparseargs全てのオプションの処理が終わった後で残った位置引数
一番普通の使い方は一切キーワード引数を使わないというものです。 values を指定した場合、それは繰り返される setattr() の呼び出し (大雑把に言うと保存される各オプション引数につき一回ずつ) で更新されていき、 parse_args() で返されます。
parse_args() が引数リストでエラーに遭遇した場合、 OptionParser の error() メソッドを適切なエンドユーザ向けのエラーメッセージとともに呼び出します。この呼び出しにより、最終的に終了ステータス 2 (伝統的な Unix におけるコマンドラインエラーの終了ステータス) でプロセスを終了させることになります。
オプション解析器への問い合わせと操作¶
オプションパーザのデフォルトの振る舞いは、ある程度カスタマイズすることができます。また、オプションパーザの中を調べることもできます。OptionParser は幾つかのヘルパーメソッドを提供しています:
- OptionParser.disable_interspersed_args()¶
Set parsing to stop on the first non-option. For example, if
-aand-bare both simple options that take no arguments,optparsenormally accepts this syntax:prog -a arg1 -b arg2
それを次と同じように扱います
prog -a -b arg1 arg2
この機能を無効にしたいときは、
disable_interspersed_args()メソッドを呼び出してください。古典的な Unix システムのように、最初のオプションでない引数を見つけたときにオプションの解析を止めるようになります。別のコマンドを実行するコマンドをプロセッサを作成する際、別のコマンドのオプションと自身のオプションが混ざるのを防ぐために利用することができます。例えば、各コマンドがそれぞれ異なるオプションのセットを持つ場合などに有効です。
- OptionParser.enable_interspersed_args()¶
オプションで無い最初の引数を見つけてもパースを止めないように設定します。オプションとコマンド引数の順序が混ざっても良いようになります。これはデフォルトの動作です。
- OptionParser.get_option(opt_str)¶
オプション文字列 opt_str に対する
Optionインスタンスを返します。該当するオプションがなければNoneを返します。
- OptionParser.has_option(opt_str)¶
OptionParserに(-qや--verboseのような) オプション opt_str がある場合、Trueを返します。
- OptionParser.remove_option(opt_str)¶
OptionParserに opt_str に対応するオプションがある場合、そのオプションを削除します。該当するオプションに他のオプション文字列が指定されていた場合、それらのオプション文字列は全て無効になります。 opt_str がこのOptionParserオブジェクトのどのオプションにも属さない場合、ValueErrorを送出します。
オプション間の衝突¶
注意が足りないと、衝突するオプションを定義してしまうことがあります:
parser.add_option("-n", "--dry-run", ...)
...
parser.add_option("-n", "--noisy", ...)
(とりわけ、OptionParser から標準的なオプションを備えた自前のサブクラスを定義してしまった場合にはよく起きます。)
Every time you add an option, optparse checks for conflicts with existing
options. If it finds any, it invokes the current conflict-handling mechanism.
You can set the conflict-handling mechanism either in the constructor:
parser = OptionParser(..., conflict_handler=handler)
個別にも呼び出せます:
parser.set_conflict_handler(handler)
衝突時の処理をおこなうハンドラ(handler)には、以下のものが利用できます:
"error"(デフォルト)オプション間の衝突をプログラム上のエラーとみなし、
OptionConflictErrorを送出します"resolve"オプション間の衝突をインテリジェントに解決します (下記参照)
一例として、衝突をインテリジェントに解決する OptionParser を定義し、衝突を起こすようなオプションを追加してみましょう:
parser = OptionParser(conflict_handler="resolve")
parser.add_option("-n", "--dry-run", ..., help="do no harm")
parser.add_option("-n", "--noisy", ..., help="be noisy")
At this point, optparse detects that a previously added option is already
using the -n option string. Since conflict_handler is "resolve",
it resolves the situation by removing -n from the earlier option's list of
option strings. Now --dry-run is the only way for the user to activate
that option. If the user asks for help, the help message will reflect that:
Options:
--dry-run do no harm
...
-n, --noisy be noisy
It's possible to whittle away the option strings for a previously added option
until there are none left, and the user has no way of invoking that option from
the command-line. In that case, optparse removes that option completely,
so it doesn't show up in help text or anywhere else. Carrying on with our
existing OptionParser:
parser.add_option("--dry-run", ..., help="new dry-run option")
At this point, the original -n/--dry-run option is no longer
accessible, so optparse removes it, leaving this help text:
Options:
...
-n, --noisy be noisy
--dry-run new dry-run option
クリーンアップ¶
OptionParser インスタンスはいくつかの循環参照を抱えています。このことは Python のガーベジコレクタにとって問題になるわけではありませんが、使い終わった OptionParser に対して destroy() を呼び出すことでこの循環参照を意図的に断ち切るという方法を選ぶこともできます。この方法は特に長時間実行するアプリケーションで OptionParser から大きなオブジェクトグラフが到達可能になっているような場合に有用です。
その他のメソッド¶
OptionParser にはその他にも幾つかの公開されたメソッドがあります:
- OptionParser.set_usage(usage)¶
上で説明したコンストラクタの
usageキーワード引数での規則に従った使用法の文字列をセットします。Noneを渡すとデフォルトの使用法文字列が使われるようになり、optparse.SUPPRESS_USAGEによって使用法メッセージを抑制できます。
- OptionParser.print_usage(file=None)¶
現在のプログラムの使用法メッセージ (
self.usage) を file (デフォルト: stdout) に表示します。self.usage内にある全ての%progという文字列は現在のプログラム名に置換されます。self.usageが空もしくは未定義の時は何もしません。
- OptionParser.get_usage()¶
print_usage()と同じですが、使用法メッセージを表示する代わりに文字列として返します。
- OptionParser.set_defaults(dest=value, ...)¶
幾つかの保存先に対してデフォルト値をまとめてセットします。
set_defaults()を使うのは複数のオプションにデフォルト値をセットする好ましいやり方です。複数のオプションが同じ保存先を共有することがあり得るからです。たとえば幾つかの "mode" オプションが全て同じ保存先をセットするものだったとすると、どのオプションもデフォルトをセットすることができ、しかし最後に指定したものだけが有効になります:parser.add_option("--advanced", action="store_const", dest="mode", const="advanced", default="novice") # overridden below parser.add_option("--novice", action="store_const", dest="mode", const="novice", default="advanced") # overrides above setting
こうした混乱を避けるために
set_defaults()を使います:parser.set_defaults(mode="advanced") parser.add_option("--advanced", action="store_const", dest="mode", const="advanced") parser.add_option("--novice", action="store_const", dest="mode", const="novice")
オプション処理コールバック¶
When optparse's built-in actions and types aren't quite enough for your
needs, you have two choices: extend optparse or define a callback option.
Extending optparse is more general, but overkill for a lot of simple
cases. Quite often a simple callback is all you need.
callback オプションの定義は二つのステップからなります:
"callback"アクションを使ってオプション自体を定義するコールバックを書く。コールバックは少なくとも後で説明する 4 つの引数をとる関数 (またはメソッド) でなければなりません
callbackオプションの定義¶
callback オプションを最も簡単に定義するには、 OptionParser.add_option() メソッドを使います。 action の他に指定しなければならない属性は callback すなわちコールバックする関数自体です:
parser.add_option("-c", action="callback", callback=my_callback)
callback is a function (or other callable object), so you must have already
defined my_callback() when you create this callback option. In this simple
case, optparse doesn't even know if -c takes any arguments,
which usually means that the option takes no arguments---the mere presence of
-c on the command-line is all it needs to know. In some
circumstances, though, you might want your callback to consume an arbitrary
number of command-line arguments. This is where writing callbacks gets tricky;
it's covered later in this section.
optparse always passes four particular arguments to your callback, and it
will only pass additional arguments if you specify them via
callback_args and callback_kwargs. Thus, the
minimal callback function signature is:
def my_callback(option, opt, value, parser):
コールバックの四つの引数については後で説明します。
callback オプションを定義する場合には、他にもいくつかオプション属性を指定できます:
typehas its usual meaning: as with the
"store"or"append"actions, it instructsoptparseto consume one argument and convert it totype. Rather than storing the converted value(s) anywhere, though,optparsepasses it to your callback function.nargsalso has its usual meaning: if it is supplied and > 1,
optparsewill consumenargsarguments, each of which must be convertible totype. It then passes a tuple of converted values to your callback.callback_argsその他の位置引数からなるタプルで、コールバックに渡されます
callback_kwargsその他のキーワード引数からなる辞書で、コールバックに渡されます
コールバック関数はどのように呼び出されるか¶
コールバックは全て以下の形式で呼び出されます:
func(option, opt_str, value, parser, *args, **kwargs)
ここでは:
optionコールバックを呼び出している
Optionのインスタンスですopt_strは、コールバック呼び出しのきっかけとなったコマンドライン上のオプション文字列です。(長い形式のオプションに対する省略形が使われている場合、
opt_strは完全な、正式な形のオプション文字列となります --- 例えば、ユーザが--foobarの短縮形として--fooをコマンドラインに入力した時には、opt_strは"--foobar"となります。)valueis the argument to this option seen on the command-line.
optparsewill only expect an argument iftypeis set; the type ofvaluewill be the type implied by the option's type. Iftypefor this option isNone(no argument expected), thenvaluewill beNone. Ifnargs> 1,valuewill be a tuple of values of the appropriate type.parser現在のオプション解析の全てを駆動している
OptionParserインスタンスです。この変数が有用なのは、この値を介してインスタンス属性としていくつかの興味深いデータにアクセスできるからです:parser.largs現在放置されている引数、すなわち、すでに消費されたものの、オプションでもオプション引数でもない引数からなるリストです。
parser.largsは自由に変更でき、たとえば引数を追加したりできます (このリストはargs、すなわちparse_args()の二つ目の戻り値になります)parser.rargs現在残っている引数、すなわち、
opt_strおよびvalueがあれば除き、それ以外の引数が残っているリストです。parser.rargsは自由に変更でき、例えばさらに引数を消費したりできます。parser.valuesthe object where option values are by default stored (an instance of optparse.OptionValues). This lets callbacks use the same mechanism as the rest of
optparsefor storing option values; you don't need to mess around with globals or closures. You can also access or modify the value(s) of any options already encountered on the command-line.
argscallback_argsオプション属性で与えられた任意の位置引数からなるタプルです。kwargscallback_kwargsオプション属性で与えられた任意のキーワード引数からなるタプルです。
コールバック中で例外を送出する¶
The callback function should raise OptionValueError if there are any
problems with the option or its argument(s). optparse catches this and
terminates the program, printing the error message you supply to stderr. Your
message should be clear, concise, accurate, and mention the option at fault.
Otherwise, the user will have a hard time figuring out what they did wrong.
コールバックの例 1: ありふれたコールバック¶
引数をとらず、発見したオプションを単に記録するだけのコールバックオプションの例を以下に示します:
def record_foo_seen(option, opt_str, value, parser):
parser.values.saw_foo = True
parser.add_option("--foo", action="callback", callback=record_foo_seen)
もちろん、"store_true" アクションを使っても実現できます。
コールバックの例 2: オプションの順番をチェックする¶
もう少し面白みのある例を示します: この例では、-b を発見して、その後で -a がコマンドライン中に現れた場合にはエラーになります。
def check_order(option, opt_str, value, parser):
if parser.values.b:
raise OptionValueError("can't use -a after -b")
parser.values.a = 1
...
parser.add_option("-a", action="callback", callback=check_order)
parser.add_option("-b", action="store_true", dest="b")
コールバックの例 3: オプションの順番をチェックする (汎用的)¶
このコールバック (フラグを立てるが、-b が既に指定されていればエラーになる) を同様の複数のオプションに対して再利用したければ、もう少し作業する必要があります: エラーメッセージとセットされるフラグを一般化しなければなりません。
def check_order(option, opt_str, value, parser):
if parser.values.b:
raise OptionValueError("can't use %s after -b" % opt_str)
setattr(parser.values, option.dest, 1)
...
parser.add_option("-a", action="callback", callback=check_order, dest='a')
parser.add_option("-b", action="store_true", dest="b")
parser.add_option("-c", action="callback", callback=check_order, dest='c')
コールバックの例 4: 任意の条件をチェックする¶
もちろん、単に定義済みのオプションの値を調べるだけにとどまらず、コールバックには任意の条件を入れられます。例えば、満月でなければ呼び出してはならないオプションがあるとしましょう。やらなければならないことはこれだけです:
def check_moon(option, opt_str, value, parser):
if is_moon_full():
raise OptionValueError("%s option invalid when moon is full"
% opt_str)
setattr(parser.values, option.dest, 1)
...
parser.add_option("--foo",
action="callback", callback=check_moon, dest="foo")
(is_moon_full() の定義は読者への課題としましょう。)
コールバックの例5: 固定引数¶
決まった数の引数をとるようなコールパックオプションを定義するなら、問題はやや興味深くなってきます。引数をとるようコールバックに指定するのは、 "store" や "append" オプションの定義に似ています。 type を定義していれば、そのオプションは引数を受け取ったときに該当する型に変換できなければなりません。さらに nargs を指定すれば、オプションは nargs 個の引数を受け取ります。
標準の "store" アクションをエミュレートする例を以下に示します:
def store_value(option, opt_str, value, parser):
setattr(parser.values, option.dest, value)
...
parser.add_option("--foo",
action="callback", callback=store_value,
type="int", nargs=3, dest="foo")
Note that optparse takes care of consuming 3 arguments and converting
them to integers for you; all you have to do is store them. (Or whatever;
obviously you don't need a callback for this example.)
コールバックの例6: 可変個の引数¶
Things get hairy when you want an option to take a variable number of arguments.
For this case, you must write a callback, as optparse doesn't provide any
built-in capabilities for it. And you have to deal with certain intricacies of
conventional Unix command-line parsing that optparse normally handles for
you. In particular, callbacks should implement the conventional rules for bare
-- and - arguments:
either
--or-can be option arguments裸の
--(何らかのオプションの引数でない場合): コマンドライン処理を停止し、--を無視します裸の
-(何らかのオプションの引数でない場合): コマンドライン処理を停止しますが、-は残します (parser.largsに追加します)
If you want an option that takes a variable number of arguments, there are
several subtle, tricky issues to worry about. The exact implementation you
choose will be based on which trade-offs you're willing to make for your
application (which is why optparse doesn't support this sort of thing
directly).
とはいえ、可変個の引数をもつオプションに対するスタブ (stub、仲介インターフェース) を以下に示しておきます:
def vararg_callback(option, opt_str, value, parser):
assert value is None
value = []
def floatable(str):
try:
float(str)
return True
except ValueError:
return False
for arg in parser.rargs:
# stop on --foo like options
if arg[:2] == "--" and len(arg) > 2:
break
# stop on -a, but not on -3 or -3.0
if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
break
value.append(arg)
del parser.rargs[:len(value)]
setattr(parser.values, option.dest, value)
...
parser.add_option("-c", "--callback", dest="vararg_attr",
action="callback", callback=vararg_callback)
Extending optparse¶
Since the two major controlling factors in how optparse interprets
command-line options are the action and type of each option, the most likely
direction of extension is to add new actions and new types.
新しい型の追加¶
To add new types, you need to define your own subclass of optparse's
Option class. This class has a couple of attributes that define
optparse's types: TYPES and TYPE_CHECKER.
- Option.TYPE_CHECKER¶
TYPE_CHECKERは辞書で型名を型チェック関数に対応付けるものです。型チェック関数は以下のようなシグネチャを持ちます:def check_mytype(option, opt, value)
ここで
optionはOptionのインスタンスであり、optはオプション文字列(たとえば-f)で、valueは望みの型としてチェックされ変換されるべくコマンドラインで与えられる文字列です。check_mytype()は想定されている型mytypeのオブジェクトを返さなければなりません。型チェック関数から返される値はOptionParser.parse_args()で返されるOptionValues インスタンスに収められるか、またはコールバックにvalueパラメータとして渡されます。型チェック関数は何か問題に遭遇したら
OptionValueErrorを送出しなければなりません。OptionValueErrorは文字列一つを引数に取り、それはそのままOptionParserのerror()メソッドに渡され、そこでプログラム名と文字列"error:"が前置されてプロセスが終了する前に stderr に出力されます。
Here's a silly example that demonstrates adding a "complex" option type to
parse Python-style complex numbers on the command line. (This is even sillier
than it used to be, because optparse 1.3 added built-in support for
complex numbers, but never mind.)
最初に必要な import 文を書きます:
from copy import copy
from optparse import Option, OptionValueError
まずは型チェック関数を定義しなければなりません。これは後で(これから定義する Option のサブクラスの TYPE_CHECKER クラス属性の中で) 参照されることになります:
def check_complex(option, opt, value):
try:
return complex(value)
except ValueError:
raise OptionValueError(
"option %s: invalid complex value: %r" % (opt, value))
最後に Option のサブクラスです:
class MyOption (Option):
TYPES = Option.TYPES + ("complex",)
TYPE_CHECKER = copy(Option.TYPE_CHECKER)
TYPE_CHECKER["complex"] = check_complex
(If we didn't make a copy() of Option.TYPE_CHECKER, we would end
up modifying the TYPE_CHECKER attribute of optparse's
Option class. This being Python, nothing stops you from doing that except good
manners and common sense.)
That's it! Now you can write a script that uses the new option type just like
any other optparse-based script, except you have to instruct your
OptionParser to use MyOption instead of Option:
parser = OptionParser(option_class=MyOption)
parser.add_option("-c", type="complex")
別のやり方として、オプションリストを構築して OptionParser に渡すという方法もあります。 add_option() を上でやったように使わないならば、OptionParser にどのクラスを使うのか教える必要はありません:
option_list = [MyOption("-c", action="store", type="complex", dest="c")]
parser = OptionParser(option_list=option_list)
新しいアクションの追加¶
Adding new actions is a bit trickier, because you have to understand that
optparse has a couple of classifications for actions:
- "store" アクション
actions that result in
optparsestoring a value to an attribute of the current OptionValues instance; these options require adestattribute to be supplied to the Option constructor.- "typed" アクション
コマンドラインから引数を受け取り、それがある型であることが期待されているアクションです。もう少しはっきり言えば、その型に変換される文字列を受け取るものです。この種類のオプションは Option のコンストラクタに
type属性を与えることが要求されます。
この分類には重複する部分があります。デフォルトの "store" アクションには "store", "store_const", "append", "count" などがありますが、デフォルトの "typed" オプションは "store", "append", "callback" の三つです。
アクションを追加する際に、以下の Option のクラス属性(全て文字列のリストです) の中の少なくとも一つに付け加えることでそのアクションを分類する必要があります:
- Option.ACTIONS¶
全てのアクションは ACTIONS にリストされていなければなりません。
- Option.STORE_ACTIONS¶
"store" アクションはここにもリストされます。
- Option.TYPED_ACTIONS¶
"typed" アクションはここにもリストされます。
- Option.ALWAYS_TYPED_ACTIONS¶
Actions that always take a type (i.e. whose options always take a value) are additionally listed here. The only effect of this is that
optparseassigns the default type,"string", to options with no explicit type whose action is listed inALWAYS_TYPED_ACTIONS.
実際に新しいアクションを実装するには、Option の take_action() メソッドをオーバライドしてそのアクションを認識する場合分けを追加しなければなりません。
例えば、"extend" アクションというのを追加してみましょう。このアクションは標準的な "append" アクションと似ていますが、コマンドラインから一つだけ値を読み取って既存のリストに追加するのではなく、複数の値をコンマ区切りの文字列として読み取ってそれらで既存のリストを拡張します。すなわち、もし --names が "string" 型の "extend" オプションだとすると、次のコマンドライン
--names=foo,bar --names blah --names ding,dong
の結果は次のリストになります
["foo", "bar", "blah", "ding", "dong"]
再び Option のサブクラスを定義します:
class MyOption(Option):
ACTIONS = Option.ACTIONS + ("extend",)
STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
def take_action(self, action, dest, opt, value, values, parser):
if action == "extend":
lvalue = value.split(",")
values.ensure_value(dest, []).extend(lvalue)
else:
Option.take_action(
self, action, dest, opt, value, values, parser)
注意すべきは次のようなところです:
"extend"はコマンドラインの値を予期していると同時にその値をどこかに格納しますので、STORE_ACTIONSとTYPED_ACTIONSの両方に入ります。to ensure that
optparseassigns the default type of"string"to"extend"actions, we put the"extend"action inALWAYS_TYPED_ACTIONSas well.MyOption.take_action()implements just this one new action, and passes control back toOption.take_action()for the standardoptparseactions.valuesは optparse_parser.Values クラスのインスタンスであり、非常に有用なensure_value()メソッドを提供しています。ensure_value()は本質的に安全弁付きのgetattr()です。次のように呼び出しますvalues.ensure_value(attr, value)
valuesにattr属性が無いかNoneだった場合に、ensure_value()は最初にvalueをセットし、それからvalueを返します。この振る舞いは"extend","append","count"のように、データを変数に集積し、またその変数がある型 (最初の二つはリスト、最後のは整数) であると期待されるアクションを作るのにとても使い易いものです。ensure_value()を使えば、作ったアクションを使うスクリプトはオプションに保存先にデフォルト値をセットすることに煩わされずに済みます。デフォルトをNoneにしておけばensure_value()がそれが必要になったときに適当な値を返してくれます。
例外¶
- exception optparse.OptionError¶
Raised if an
Optioninstance is created with invalid or inconsistent arguments.
- exception optparse.OptionConflictError¶
Raised if conflicting options are added to an
OptionParser.
- exception optparse.OptionValueError¶
Raised if an invalid option value is encountered on the command line.
- exception optparse.BadOptionError¶
Raised if an invalid option is passed on the command line.
- exception optparse.AmbiguousOptionError¶
Raised if an ambiguous option is passed on the command line.