optparse — 명령 줄 옵션용 구문 분석기

소스 코드: Lib/optparse.py


Choosing an argument parsing library

The standard library includes three argument parsing libraries:

  • getopt: a module that closely mirrors the procedural C getopt API. Included in the standard library since before the initial Python 1.0 release.

  • optparse: a declarative replacement for getopt that 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 to optparse that 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 optparse and doesn’t want to risk the subtle behavioural changes that may arise when migrating to argparse

  • the 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 argparse does 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 argparse does not support, but which can be implemented in terms of the lower level interface offered by optparse

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 -v gives output="-v" and verbose=False when using optparse, but a usage error with argparse (complaining that no value has been supplied for -o/--output, since -v is interpreted as meaning the verbosity flag)

  • similarly, supplying -o -- gives output="--" and args=() when using optparse, but a usage error with argparse (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=foo gives output="=foo" when using optparse, but gives output="foo" with argparse (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.

Introduction

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()로 전달한 문자열. 파이썬에서, 인자는 sys.argv[1:]의 요소입니다 (sys.argv[0]은 실행 중인 프로그램의 이름입니다). 유닉스 셸은 “워드(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. -x or -F. Also, traditional Unix syntax allows multiple options to be merged into a single argument, e.g. -x -F is equivalent to -xF. The GNU project introduced -- followed by a series of hyphen-separated words, e.g. --file or --dry-run. These are the only two option syntaxes provided by optparse.

세상에 등장했던 다른 옵션 문법은 다음과 같습니다:

  • 몇 개의 문자가 뒤따르는 하이픈, 예를 들어 -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 -a takes an optional argument and -b is another option entirely, how do we interpret -ab? Because of this ambiguity, optparse does 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. optparse doesn’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는 옵션 인자입니다. foobar는 위치 인자입니다.

옵션은 무엇을 위한 것입니까?

옵션은 프로그램 실행을 조정하거나 사용자 정의하기 위한 추가 정보를 제공하는 데 사용됩니다. 명확하지 않은 경우, 옵션은 일반적으로 선택적입니다. 프로그램은 어떤 옵션도 없이 잘 실행될 수 있어야 합니다. (유닉스나 GNU 도구 집합에서 임의의 프로그램을 선택하십시오. 옵션 없이도 실행될 수 있으며 여전히 의미가 있습니까? 주요 예외는 find, tardd입니다 — 모두 비표준 문법과 혼란스러운 인터페이스 때문에 올바로 비판을 받은 돌연변이 괴짜입니다.)

많은 사람이 프로그램에 “필수 옵션”이 있기를 원합니다. 생각해보십시오. 필수라면, 그것은 선택적(optional)이 아닙니다! 당신의 프로그램이 성공적으로 실행하기 위해 절대적으로 필요한 정보가 있다면, 그것이 바로 위치 인자의 목적입니다.

좋은 명령 줄 인터페이스 설계의 예로, 파일 복사를 위한 겸손한 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 클래스를 임포트 해야 합니다; 그런 다음 메인 프로그램의 초기에, 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()에 전달할 수 있지만, 거의 필요하지 않습니다: 기본적으로 sys.argv[1:]을 사용합니다.)

parse_args()는 두 가지 값을 반환합니다:

  • options, 모든 옵션에 대한 값을 포함하는 객체—예를 들어 --file이 단일 문자열 인자를 취하면, options.file은 사용자가 제공한 파일명이거나, 사용자가 해당 옵션을 제공하지 않으면 None입니다.

  • args, 옵션 구문 분석 후 남은 위치 인자 리스트

이 자습서 섹션에서는 가장 중요한 4가지 옵션 어트리뷰트만 다룹니다: 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이기 때문에 명시적인 액션이 없습니다.

다른 가짜 명령 줄을 구문 분석해 봅시다. 이번에는, 옵션 인자를 옵션 바로 다음에 붙일 것입니다: -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")

기본값은 특정 옵션이 아닌 대상(destination)에 적용되고, 이 두 옵션은 같은 대상을 갖기 때문에, 다음과 정확히 동등합니다:

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"
    

    optparse expands %prog in 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, optparse uses 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—optparse takes care of wrapping lines and making the help output look good.

  • 값을 취하는 옵션은 자동으로 생성된 도움말 메시지에 이 사실을 나타냅니다, 예를 들어 “mode” 옵션의 경우:

    -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, optparse converts the destination variable name to uppercase and uses that for the meta-variable. Sometimes, that’s not what you want—for example, the --filename option explicitly sets metavar="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 %default in the help string—optparse will replace it with str() of the option’s default value. If an option has no default value (or the default value is None), %default expands to none.

옵션 그룹화하기

많은 옵션을 다룰 때, 더 나은 도움말 출력을 위해 이러한 옵션을 그룹화하는 것이 편리합니다. 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

특히 옵션 그룹을 프로그래밍 방식으로 작업할 때, 또 다른 흥미로운 메서드는 다음과 같습니다:

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

다음 두 가지 메서드를 사용하여 version 문자열을 인쇄하고 가져올 수 있습니다:

OptionParser.print_version(file=None)

현재 프로그램의 버전 메시지(self.version)를 file(기본값은 표준 출력)로 인쇄합니다. 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()

레퍼런스 지침서

구문 분석기 만들기

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 optparse prints the usage string, it expands %prog to os.path.basename(sys.argv[0]) (or to prog if you passed that keyword argument). To suppress a usage message, pass the special value optparse.SUPPRESS_USAGE.

option_list (기본값: [])

구문 분석기를 채울 Option 객체 리스트. option_list의 옵션은 standard_option_list(OptionParser 서브 클래스에서 설정할 수 있는 클래스 어트리뷰트)의 모든 옵션 뒤에 추가되지만, 모든 버전(version) 또는 도움말(help) 옵션 앞에 추가됩니다. 폐지되었습니다; 대신 구문 분석기를 만든 후 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, optparse automatically adds a version option with the single option string --version. The substring %prog is expanded the same as for usage.

conflict_handler (기본값: "error")

충돌하는 옵션 문자열이 있는 옵션이 구문 분석기에 추가될 때 수행 할 작업을 지정합니다; 섹션 옵션 간의 충돌을 참조하십시오.

description (기본값: None)

A paragraph of text giving a brief overview of your program. optparse reformats this paragraph to fit the current terminal width and prints it when the user requests help (after usage, but before the list of options).

formatter (기본값: 새 IndentedHelpFormatter)

An instance of optparse.HelpFormatter that will be used for printing help text. optparse provides two concrete classes for this purpose: IndentedHelpFormatter and TitledHelpFormatter.

add_help_option (기본값: True)

If true, optparse will add a help option (with option strings -h and --help) to the parser.

prog

usageversion에서 %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 인스턴스를 만드는 규범적 방법은 OptionParseradd_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, optparse raises an OptionError exception explaining your mistake.

An option’s action determines what optparse does when it encounters this option on the command-line. The standard option actions hard-coded into optparse are:

"store"

이 옵션의 인자를 저장합니다 (기본값)

"store_const"

store a constant value, pre-set via Option.const

"store_true"

True를 저장합니다

"store_false"

False를 저장합니다

"append"

이 옵션의 인자를 리스트에 추가합니다

"append_const"

리스트에 상숫값을 추가합니다, Option.const로 사전 설정

"count"

카운터를 1씩 증가시킵니다

"callback"

지정된 함수를 호출합니다

"help"

모든 옵션과 해당 설명을 포함하는 사용법 메시지를 인쇄합니다

(액션을 제공하지 않으면, 기본값은 "store"입니다. 이 액션의 경우, typedest 옵션 어트리뷰트도 제공할 수 있습니다; 표준 옵션 액션을 참조하십시오.)

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 of OptionParser.parse_args() (as described in 인자 구문 분석하기).

옵션 인자(및 기타 다양한 값)는 dest (destination) 옵션 어트리뷰트에 따라, 이 객체의 어트리뷰트로 저장됩니다.

예를 들어, 다음과 같이 호출할 때

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"

typedest 옵션 어트리뷰트는 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 to OptionParser.

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 optparse where to write it: dest names an attribute of the options object that optparse builds as it parses the command line.

Option.default

옵션이 명령 줄에서 보이지 않으면 이 옵션의 대상에 사용할 값. OptionParser.set_defaults()도 참조하십시오.

Option.nargs

(기본값: 1)

How many arguments of type type should be consumed when this option is seen. If > 1, optparse will store a tuple of values to dest.

Option.const

상숫값을 저장하는 액션의 경우, 저장할 상숫값.

Option.choices

"choice" 형 옵션의 경우, 사용자가 이 중에서 선택할 수 있는 문자열 리스트.

Option.callback

액션 "callback"이 있는 옵션의 경우, 이 옵션이 보일 때 호출 할 콜러블. 콜러블에 전달된 인자에 대한 자세한 내용은 섹션 옵션 콜백을 참조하십시오.

Option.callback_args
Option.callback_kwargs

4개의 표준 콜백 인자 다음에 callback에 전달할 추가 위치와 키워드 인자.

Option.help

사용자가 help 옵션을 제공한 (가령 --help) 후 사용 가능한 모든 옵션을 나열할 때 이 옵션에 대해 인쇄할 도움말 텍스트. 도움말 텍스트가 제공되지 않으면, 옵션이 도움말 텍스트 없이 나열됩니다. 이 옵션을 숨기려면, 특수 값 optparse.SUPPRESS_HELP를 사용하십시오.

Option.metavar

(기본값: 옵션 문자열에서 파생됩니다)

도움말 텍스트를 인쇄할 때 사용할 옵션 인자를 나타냅니다. 예제는 섹션 자습서를 참조하십시오.

표준 옵션 액션

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 dest is not supplied, optparse derives a destination from the first long option string (e.g., --foo-bar implies foo_bar). If there are no long option strings, optparse derives a destination from the first short option string (e.g., -f implies f).

    예:

    parser.add_option("-f")
    parser.add_option("-p", type="float", nargs=3, dest="point")
    

    다음과 같은 명령 줄을 구문 분석할 때

    -f foo.txt -p 1 -3.5 4 -fbar.txt
    

    optparse will set

    options.f = "foo.txt"
    options.point = (1.0, -3.5, 4.0)
    options.f = "bar.txt"
    
  • "store_const" [필수 옵션: const; 연관된 옵션: dest]

    constdest에 저장됩니다.

    예:

    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 --noisy is seen, optparse will set

    options.verbose = 2
    
  • "store_true" [연관된 옵션: dest]

    Truedest에 저장하는 "store_const"의 특별한 경우.

  • "store_false" [연관된 옵션: dest]

    "store_true"와 비슷하지만, False를 저장합니다.

    예:

    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 for dest is supplied, an empty list is automatically created when optparse first encounters this option on the command-line. If nargs > 1, multiple arguments are consumed, and a tuple of length nargs is appended to dest.

    typedest의 기본값은 "store" 액션의 경우와 같습니다.

    예:

    parser.add_option("-t", "--tracks", action="append", type="int")
    

    If -t3 is seen on the command-line, optparse does 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"와 마찬가지로, dest의 기본값은 None이며, 옵션이 처음 발견될 때 빈 리스트가 자동으로 만들어집니다.

  • "count" [연관된 옵션: dest]

    dest에 저장된 정수를 증가시킵니다. 기본값이 제공되지 않으면, dest는 처음으로 증가하기 전에 0으로 설정됩니다.

    예:

    parser.add_option("-v", action="count", dest="verbosity")
    

    The first time -v is seen on the command line, optparse does 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를 사용하십시오.

    optparse automatically adds a help option to all OptionParsers, so you do not normally need to create one.

    예:

    from optparse import OptionParser, SUPPRESS_HELP
    
    # 일반적으로, 도움말 옵션은 자동으로 추가되지만, add_help_option 인자를
    # 사용하여 억제할 수 있습니다
    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 optparse sees either -h or --help on the command line, it will print something like the following help message to stdout (assuming sys.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, optparse terminates your process with sys.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 the version argument is supplied to the OptionParser constructor. As with help options, you will rarely create version options, since optparse automatically 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로 시작하면, 이진수로 구문 분석됩니다

  • 그렇지 않으면, 숫자는 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.

입력 매개 변수는

args

처리할 인자의 리스트 (기본값: sys.argv[1:])

values

옵션 인자를 저장할 Values 객체 (기본값: Values의 새 인스턴스) – 기존 객체를 제공하면, 옵션 기본값이 초기화되지 않습니다.

그리고 반환 값은 쌍 (options, args)이고

options

the same object that was passed in as values, or the optparse.Values instance created by optparse

args

모든 옵션이 처리된 후 남은 위치 인자

가장 일반적인 사용법은 두 키워드 인자 중 어느 것도 제공하지 않는 것입니다. values를 제공하면, 반복된 setattr() 호출(옵션 대상에 저장된 모든 옵션 인자에 대해 대략 하나씩)로 수정되고, parse_args()에서 반환됩니다.

parse_args()가 인자 리스트에서 에러를 만나면, 적절한 최종 사용자 에러 메시지와 함께 OptionParser의 error() 메서드를 호출합니다. 이는 궁극적으로 종료 상태 2(명령 줄 에러에 대한 전통적인 유닉스 종료 상태)로 프로세스를 종료합니다.

옵션 구문 분석기를 조회하고 조작하기

옵션 구문 분석기의 기본 동작은 약간 사용자 정의 할 수 있으며, 옵션 구문 분석기를 들여다보고 거기에 무엇이 있는지 볼 수도 있습니다. OptionParser는 다음과 같은 몇 가지 메서드를 제공합니다:

OptionParser.disable_interspersed_args()

Set parsing to stop on the first non-option. For example, if -a and -b are both simple options that take no arguments, optparse normally accepts this syntax:

prog -a arg1 -b arg2

그리고 다음과 동등하게 취급합니다

prog -a -b arg1 arg2

이 기능을 비활성화하려면, disable_interspersed_args()를 호출하십시오. 이렇게 하면 옵션 구문 분석이 첫 번째 옵션이 아닌 인자에서 중지되는, 전통적인 유닉스 문법이 복원됩니다.

자체 옵션이 있는 다른 명령을 실행하는 명령 프로세서가 있고 이러한 옵션이 혼동되지 않도록 하려면 이것을 사용하십시오. 예를 들어, 각 명령에는 다른 옵션 집합이 있을 수 있습니다.

OptionParser.enable_interspersed_args()

첫 번째 옵션이 아닌 것에서 구문 분석이 중지되지 않도록 설정하여, 명령 인자와 스위치를 분산시킬 수 있도록 합니다. 이것이 기본 동작입니다.

OptionParser.get_option(opt_str)

옵션 문자열 opt_str을 갖는 Option 인스턴스를 반환합니다, 또는 해당 옵션 문자열을 갖는 옵션이 없으면 None을 반환합니다.

OptionParser.has_option(opt_str)

OptionParser에 옵션 문자열 opt_str을 갖는 옵션이 있으면 True를 반환합니다 (예를 들어, -q--verbose).

OptionParser.remove_option(opt_str)

OptionParseropt_str에 해당하는 옵션이 있으면, 해당 옵션이 제거됩니다. 해당 옵션이 다른 옵션 문자열을 제공하면, 해당 옵션 문자열은 모두 유효하지 않게 됩니다. 이 OptionParser에 속하는 옵션에서 opt_str이 등장하지 않으면, 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)

사용 가능한 충돌 처리기는 다음과 같습니다:

"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 인스턴스에는 여러 순환 참조가 있습니다. 이것은 파이썬의 가비지 수거기에선 문제가 되지 않지만, 작업이 끝나면 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")    # 아래에서 재정의됩니다
parser.add_option("--novice", action="store_const",
                  dest="mode", const="novice",
                  default="advanced")  # 위의 설정을 재정의합니다

이러한 혼동을 피하려면, 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" 액션을 사용하여 옵션 자체를 정의합니다

  • 콜백을 작성합니다; 이것은 아래에 설명된 대로, 최소한 4개의 인자를 취하는 함수(또는 메서드)입니다

콜백 옵션 정의하기

항상 그렇듯이, 콜백 옵션을 정의하는 가장 쉬운 방법은 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):

콜백에 대한 네 가지 인자가 아래에 설명되어 있습니다.

콜백 옵션을 정의할 때 제공할 수 있는 몇 가지 다른 옵션 어트리뷰트가 있습니다:

type

has its usual meaning: as with the "store" or "append" actions, it instructs optparse to consume one argument and convert it to type. Rather than storing the converted value(s) anywhere, though, optparse passes it to your callback function.

nargs

also has its usual meaning: if it is supplied and > 1, optparse will consume nargs arguments, each of which must be convertible to type. 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"가 됩니다.)

value

is the argument to this option seen on the command-line. optparse will only expect an argument if type is set; the type of value will be the type implied by the option’s type. If type for this option is None (no argument expected), then value will be None. If nargs > 1, value will be a tuple of values of the appropriate type.

parser

모든 것을 구동하는 OptionParser 인스턴스입니다, 인스턴스 어트리뷰트를 통해 다른 흥미로운 데이터에 액세스 할 수 있어서 주로 유용합니다:

parser.largs

남은 인자의 현재 리스트, 즉, 소비되었지만 옵션이나 옵션 인자가 아닌 인자. 예를 들어 더 많은 인자를 추가하여, parser.largs를 자유롭게 수정하십시오. (이 리스트는 parse_args()의 두 번째 반환 값인 args가 됩니다.)

parser.rargs

나머지 인자의 현재 리스트, 즉, opt_strvalue(해당한다면)가 제거되고, 그 뒤에 오는 인자만 그대로 남아 있습니다. 예를 들어 더 많은 인자를 소비하여, parser.rargs를 자유롭게 수정하십시오.

parser.values

the object where option values are by default stored (an instance of optparse.OptionValues). This lets callbacks use the same mechanism as the rest of optparse for 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.

args

callback_args 옵션 어트리뷰트를 통해 제공되는 임의의 위치 인자의 튜플입니다.

kwargs

callback_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: 옵션 순서 확인

여기에 약간 더 흥미로운 예가 있습니다: -a가 발견되었다는 사실을 기록하지만, 명령 줄에서 -b 뒤에 오면 폭발합니다.

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:

  • ---는 옵션 인자가 될 수 있습니다

  • -- (어떤 옵션에 대한 인자가 아닌 경우): 명령 줄 처리를 중단하고 --를 버립니다

  • - (어떤 옵션에 대한 인자가 아닌 경우): 명령 줄 처리를 중지하지만 -는 유지합니다 (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).

그런데도, 가변 인자가 있는 옵션에 대한 콜백에는 가시가 있습니다:

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:
        # --foo 와 같은 옵션에서 멈춥니다
        if arg[:2] == "--" and len(arg) > 2:
            break
        # -a 에서 멈추지만, -3 이나 -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.TYPES

형 이름의 튜플; 여러분의 서브 클래스에서, 표준 튜플을 기반으로 하는 새 튜플 TYPES를 정의하십시오.

Option.TYPE_CHECKER

형 이름을 형 검사 함수에 매핑하는 딕셔너리. 형 검사 함수는 다음과 같은 서명을 갖습니다:

def check_mytype(option, opt, value)

여기서 optionOption 인스턴스이고, opt는 옵션 문자열(예를 들어, -f)이며, value는 검사되고 원하는 형으로 변환되어야 하는 명령 줄의 문자열입니다. check_mytype()은 가상의 형 mytype의 객체를 반환해야 합니다. 형 검사 함수가 반환한 값은 OptionParser.parse_args()에서 반환한 OptionValues 인스턴스에 포함되거나 value 매개 변수로 콜백에 전달됩니다.

형 검사 함수는 문제가 발생하면 OptionValueError 를 발생시켜야 합니다. OptionValueErrorOptionParsererror() 메서드에 있는 그대로 전달되는 단일 문자열 인자를 취하며, 이는 차례로 프로그램 이름과 문자열 "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.)

첫째, 필요한 임포트:

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:

“저장” 액션

actions that result in optparse storing a value to an attribute of the current OptionValues instance; these options require a dest attribute to be supplied to the Option constructor.

“형이 있는” 액션

명령 줄에서 값을 취하고 이것이 특정 형일 것으로 기대하는 액션; 또는, 특정 형으로 변환할 수 있는 문자열. 이러한 옵션을 사용하려면 Option 생성자에 type 어트리뷰트를 제공해야 합니다.

이들은 겹치는 집합입니다: 일부 기본 “저장” 액션은 "store", "store_const", "append""count"이고, 기본 “형이 있는” 액션은 "store", "append""callback"입니다.

액션을 추가할 때, Option의 다음 클래스 어트리뷰트 중 하나 이상에 나열하여 분류해야 합니다 (모두 문자열 리스트입니다):

Option.ACTIONS

모든 액션은 ACTIONS에 나열되어야 합니다.

Option.STORE_ACTIONS

“저장” 액션이 여기에 추가로 나열됩니다.

Option.TYPED_ACTIONS

“형이 있는” 액션이 여기에 추가로 나열됩니다.

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 optparse assigns the default type, "string", to options with no explicit type whose action is listed in ALWAYS_TYPED_ACTIONS.

새 액션을 실제로 구현하려면, Option의 take_action() 메서드를 재정의하고 액션을 인식하는 케이스를 추가해야 합니다.

예를 들어, "extend" 액션을 추가해 보겠습니다. 이것은 표준 "append" 액션과 유사하지만, 명령 줄에서 단일 값을 취해서 기존 리스트에 추가하는 대신, "extend"는 단일 쉼표로 구분된 문자열에서 여러 값을 취해서 기존 리스트를 확장합니다. 즉, --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_ACTIONSTYPED_ACTIONS 모두에 들어갑니다.

  • to ensure that optparse assigns the default type of "string" to "extend" actions, we put the "extend" action in ALWAYS_TYPED_ACTIONS as well.

  • MyOption.take_action() implements just this one new action, and passes control back to Option.take_action() for the standard optparse actions.

  • values는 매우 유용한 ensure_value() 메서드를 제공하는 optparse_parser.Values 클래스의 인스턴스입니다. ensure_value()는 본질적으로 안전밸브가 있는 getattr()입니다; 다음과 같이 호출됩니다

    values.ensure_value(attr, value)
    

    valuesattr 어트리뷰트가 존재하지 않거나 None이면, ensure_value()는 먼저 이를 value로 설정한 다음, value를 반환합니다. 이것은 "extend", "append""count"와 같은 액션에 매우 편리합니다. 이 액션들은 모두 변수에 데이터를 누적하고 해당 변수가 특정 형(처음 두 개는 리스트, 마지막은 정수)이 될 것으로 기대합니다. ensure_value()를 사용한다는 것은 액션을 사용하는 스크립트가 문제의 옵션 대상에 대한 기본값 설정에 대해 걱정할 필요가 없음을 의미합니다; 기본값을 None으로 그대로 둘 수 있으며 ensure_value()는 필요할 때 올바르게 처리합니다.

예외

exception optparse.OptionError

Raised if an Option instance 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

명령줄에서 잘못된 옵션이 전달되면 발생합니다.

exception optparse.AmbiguousOptionError

Raised if an ambiguous option is passed on the command line.