pytho****@googl*****
pytho****@googl*****
2011年 3月 7日 (月) 23:54:39 JST
Revision: 09cffe954e Author: INADA Naoki <inada****@klab*****> Date: Mon Mar 7 06:41:07 2011 Log: レビュー: tutorial/stdlib.rst http://code.google.com/p/python-doc-ja/source/detail?r=09cffe954e Modified: /tutorial/stdlib.rst ======================================= --- /tutorial/stdlib.rst Thu Feb 10 23:46:35 2011 +++ /tutorial/stdlib.rst Mon Mar 7 06:41:07 2011 @@ -7,11 +7,11 @@ .. _tut-os-interface: -オペレーティングシステムへのインタフェース -========================================== +OSへのインタフェース +====================== :mod:`os` モジュールは、オペレーティングシステムと対話するための -何ダースもの関数を提供しています: +何ダースもの関数を提供しています。 :: @@ -22,32 +22,25 @@ 'C:\\Python26' >>> os.chdir('/server/accesslogs') -``from os import *`` ではなく、 ``import os`` 形式を使うようにしてくださ い。そうすることで、 -動作が大きく異なる組み込み関数 :func:`open` が :func:`os.open` で隠蔽される のを避けられます。 - -.. % % Be sure to use the \samp{import os} style instead of -.. % % \samp{from os import *}. This will keep \function{os.open()} from -.. % % shadowing the builtin \function{open()} function which operates much -.. % % differently. +``from os import *`` ではなく、 ``import os`` 形式を使うようにしてくださ い。 +そうすることで、動作が大きく異なる組み込み関数 :func:`open` が :func:`os.open` +で隠蔽されるのを避けられます。 .. index:: builtin: help -組み込み関数 :func:`dir` および :func:`help` は、 :mod:`os` のような大規模 なモジュールで作業をするときに、対話的な -操作上の助けになります: - -.. % % The builtin \function{dir()} and \function{help()} functions are useful -.. % % as interactive aids for working with large modules like \module{os}: +組み込み関数 :func:`dir` および :func:`help` は、 :mod:`os` のような大規模 な +モジュールで作業をするときに、対話的な操作上の助けになります。 :: >>> import os >>> dir(os) - <returns a list of all module functions> + <モジュール内の関数全てを含むリストを返す> >>> help(os) - <returns an extensive manual page created from the module's docstrings> - -ファイルやディレクトリの日常的な管理作業のために、より簡単に使える高レベル インタフェースが -:mod:`shutil` モジュールで提供されています。 + <モジュールの docstring から作られた広範囲に渡るマニュアルページを返す> + +ファイルやディレクトリの日常的な管理作業のために、より簡単に使える高レベル +インタフェースが :mod:`shutil` モジュールで提供されています。 :: @@ -62,11 +55,8 @@ ============================ :mod:`glob` モジュールでは、 -ディレクトリのワイルドカード検索からファイルのリストを生成するための関数を 提供しています: - -.. % % The \ulink{\module{glob}}{../lib/module-glob.html} -.. % % module provides a function for making file lists from directory -.. % % wildcard searches: +ディレクトリのワイルドカード検索からファイルのリストを生成するための +関数を提供しています。 :: @@ -80,15 +70,11 @@ コマンドライン引数 ================== -広く使われているユーティリティスクリプトでは、しばしばコマンドライン引数の 処理を呼び出します。 -これらの引数は :mod:`sys` モジュールの *argv* 属性にリストとして記憶されま す。 -例えば、以下の出力は、 ``python demo.py one two three`` をコマンドライン上 で起動した際に得られるものです: - -.. % % Common utility scripts often need to process command line arguments. -.. % % These arguments are stored in the -.. % % \ulink{\module{sys}}{../lib/module-sys.html}\ module's \var{argv} -.. % % attribute as a list. For instance the following output results from -.. % % running \samp{python demo.py one two three} at the command line: +一般的なユーティリティスクリプトでは、よくコマンドライン引数を扱う必要が +あります。コマンドライン引数は :mod:`sys` モジュールの *argv* 属性に +リストとして保存されています。 +例えば、以下の出力は、 ``python demo.py one two three`` とコマンドライン上 で +起動した時に得られるものです。 :: @@ -96,15 +82,9 @@ >>> print sys.argv ['demo.py', 'one', 'two', 'three'] -:mod:`getopt` モジュールは、 *sys.argv* を -Unix の :func:`getopt` 関数の慣習に従って処理します。より強力で柔軟性のある コマンドライン処理機能は、 :mod:`optparse` -モジュールで提供されています。 - -.. % % The \ulink{\module{getopt}}{../lib/module-getopt.html} -.. % % module processes \var{sys.argv} using the conventions of the \UNIX{} -.. % % \function{getopt()} function. More powerful and flexible command line -.. % % processing is provided by the -.. % % \ulink{\module{optparse}}{../lib/module-optparse.html} module. +:mod:`getopt` モジュールは、 *sys.argv* を Unix の :func:`getopt` 関数の慣 習に +従って処理します。より強力で柔軟性のあるコマンドライン処理機能は、 +:mod:`optparse` モジュールで提供されています。 .. _tut-stderr: @@ -112,14 +92,9 @@ エラー出力のリダイレクトとプログラムの終了 ========================================== -:mod:`sys` モジュールには、 *stdin*, *stdout*, *stderr* を表す属性値も存在 します。 -後者の *stderr* は、警告やエラーメッセージを出力して、 *stdout* -がリダイレクトされた場合でもそれらが読めるようにする上で便利です: - -.. % % The \ulink{\module{sys}}{../lib/module-sys.html} -.. % % module also has attributes for \var{stdin}, \var{stdout}, and -.. % % \var{stderr}. The latter is useful for emitting warnings and error -.. % % messages to make them visible even when \var{stdout} has been redirected: +:mod:`sys` モジュールには、 *stdin*, *stdout*, *stderr* を表す属性も存在し ます。 +*stderr* は、警告やエラーメッセージを出力して、 *stdout* がリダイレクトされ た +場合でも読めるようにするために便利です。 :: @@ -128,22 +103,14 @@ ``sys.exit()`` は、スクリプトを終了させるもっとも直接的な方法です。 -.. % % The most direct way to terminate a script is to use \samp{sys.exit()}. - .. _tut-string-pattern-matching: 文字列のパターンマッチング ========================== -:mod:`re` モジュールでは、より高度な文字列処理のための正規表現 -(regular expression) を提供しています。 -正規表現は複雑な一致検索や操作に対して簡潔で最適化された解決策を与えます: - -.. % % The \ulink{\module{re}}{../lib/module-re.html} -.. % % module provides regular expression tools for advanced string processing. -.. % % For complex matching and manipulation, regular expressions offer succinct, -.. % % optimized solutions: +:mod:`re` モジュールでは、より高度な文字列処理のための正規表現を提供してい ます。 +正規表現は複雑な一致検索や操作に対して簡潔で最適化された解決策を提供しま す。 :: @@ -153,10 +120,8 @@ >>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat') 'cat in the hat' -最小限の機能だけが必要なら、読みやすくデバッグしやすい文字列メソッドの方が お勧めです: - -.. % % When only simple capabilities are needed, string methods are preferred -.. % % because they are easier to read and debug: +最小限の機能だけが必要なら、読みやすくデバッグしやすい文字列メソッドの方が +お勧めです。 :: @@ -169,8 +134,8 @@ 数学 ==== -:mod:`math` モジュールでは、根底にある浮動小数点演算のための C -言語ライブラリ関数にアクセスする手段を提供しています: +:mod:`math` モジュールは、浮動小数点演算のための C 言語ライブラリ関数に +アクセスする手段を提供しています。 :: @@ -180,10 +145,8 @@ >>> math.log(1024, 2) 10.0 -:mod:`random` モジュールでは、乱数に基づいた要素選択のためのツールを提供し ています: - -.. % % The \ulink{\module{random}}{../lib/module-random.html} -.. % % module provides tools for making random selections: +:mod:`random` モジュールは、乱数に基づいた要素選択のためのツールを +提供しています。 :: @@ -203,16 +166,16 @@ インターネットへのアクセス ========================== -インターネットにアクセスしたり、インターネットプロトコルを処理したりするた めの数多くのモジュールがあります。 -その中でも特にシンプルなモジュールとして、URL -を指定してデータを取得するための :mod:`urllib2` -と、メールを送信するための :mod:`smtplib` があります。 +インターネットにアクセスしたり、インターネットプロトコルを処理したりするた めの +数多くのモジュールがあります。その中でも特にシンプルなモジュールとして、URL +を指定してデータを取得するための :mod:`urllib2` と、メールを送信するための +:mod:`smtplib` があります。 :: >>> import urllib2 >>> for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'): - ... if 'EST' in line or 'EDT' in line: # look for Eastern Time + ... if 'EST' in line or 'EDT' in line: # EST(東部標準時)を見る ... print line <BR>Nov. 25, 09:43:32 PM EST @@ -227,7 +190,8 @@ ... """) >>> server.quit() -(2つ目の例は localhost でメールサーバーが動いている必要があることに注意して ください。) +(2つ目の例は localhost でメールサーバーが動いている必要があることに注意して +ください。) .. _tut-dates-and-times: @@ -235,21 +199,14 @@ 日付と時刻 ========== -:mod:`datetime` モジュールは、 -日付や時刻を操作するためのクラスを、単純な方法と複雑な方法の両方で供給して います。日付や時刻に対する算術がサポートされている一方、 -実装では出力の書式化や操作のための効率的なデータメンバ抽出に重点を置いてい ます。このモジュールでは、タイムゾーンに対応したオブジェクトもサポート -しています。 - -.. % % The \ulink{\module{datetime}}{../lib/module-datetime.html} module -.. % % supplies classes for manipulating dates and times in both simple -.. % % and complex ways. While date and time arithmetic is supported, the -.. % % focus of the implementation is on efficient member extraction for -.. % % output formatting and manipulation. The module also supports objects -.. % % that are time zone aware. +:mod:`datetime` モジュールは、日付や時刻を操作するためのクラスを、単純な方 法と +複雑な方法の両方で提供しています。日付や時刻に対する算術がサポートされてい る一方、 +実装では出力の書式化や操作のための効率的なデータメンバ抽出に重点を置いてい ます。 +このモジュールでは、タイムゾーンに対応したオブジェクトもサポートしていま す。 :: - >>> # dates are easily constructed and formatted + >>> # 日付は簡単に生成して書式化することができます。 >>> from datetime import date >>> now = date.today() >>> now @@ -257,7 +214,7 @@ >>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B") '12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December' - >>> # dates support calendar arithmetic + >>> # date 型はカレンダー計算をサポートしています。 >>> birthday = date(1964, 7, 31) >>> age = now - birthday >>> age.days @@ -269,16 +226,9 @@ データ圧縮 ========== -データの書庫化や圧縮で広く使われている形式については、 :mod:`zlib`, -:mod:`gzip`, :mod:`bz2`, :mod:`zipfile`, :mod:`tarfile` といったモジュール で直接サポートしています。 - -.. % % Common data archiving and compression formats are directly supported -.. % % by modules including: -.. % % \ulink{\module{zlib}}{../lib/module-zlib.html}, -.. % % \ulink{\module{gzip}}{../lib/module-gzip.html}, -.. % % \ulink{\module{bz2}}{../lib/module-bz2.html}, -.. % % \ulink{\module{zipfile}}{../lib/module-zipfile.html}, and -.. % % \ulink{\module{tarfile}}{../lib/module-tarfile.html}. +データの書庫化や圧縮で広く使われている形式について は、 :mod:`zlib`, :mod:`gzip`, +:mod:`bz2`, :mod:`zipfile`, :mod:`tarfile` といったモジュールで直接サポート して +います。 :: @@ -300,21 +250,14 @@ パフォーマンスの計測 ==================== -Python ユーザの中には、同じ問題を異なったアプローチで解いた際の相対的なパフ ォーマンスについて知りたいという深い興味を -持っている人がいます。Python では、そういった疑問に即座に答える計測ツールを 提供しています。 - -.. % % Some Python users develop a deep interest in knowing the relative -.. % % performance between different approaches to the same problem. -.. % % Python provides a measurement tool that answers those questions -.. % % immediately. - -例えば、引数の入れ替え操作に対して、伝統的なアプローチの代わりにタプルのパ ックやアンパックを使ってみたい気持ちになるかもしれません。 -:mod:`timeit` モジュールを使えば、パフォーマンス上の利点はほぼ互角だとわか ります: - -.. % % For example, it may be tempting to use the tuple packing and unpacking -.. % % feature instead of the traditional approach to swapping arguments. -.. % % The \ulink{\module{timeit}}{../lib/module-timeit.html} module -.. % % quickly demonstrates a modest performance advantage: +Python ユーザの中には、同じ問題を異なったアプローチで解いた際の相対的な +パフォーマンスについて知りたいという深い興味を持っている人がいます。 +Python は、そういった疑問に即座に答える計測ツールを提供しています。 + +例えば、引数の入れ替え操作に対して、伝統的なアプローチの代わりにタプルの +パックやアンパックを使ってみたいと思うかもしれません。 +:mod:`timeit` モジュールを使えば、パフォーマンスがほんの少し良いことが +すぐに分かります。 :: @@ -324,38 +267,25 @@ >>> Timer('a,b = b,a', 'a=1; b=2').timeit() 0.54962537085770791 -:mod:`timeit` では高い粒度レベルを提供しているのに対し、 :mod:`profile` や +:mod:`timeit` では小さい粒度を提供しているのに対し、 :mod:`profile` や :mod:`pstats` モジュールではより大きなコードブロックにおいて律速となる部分 を 判定するためのツールを提供しています。 -.. % % In contrast to \module{timeit}'s fine level of granularity, the -.. % % \ulink{\module{profile}}{../lib/module-profile.html} and \module{pstats} -.. % % modules provide tools for identifying time critical sections in larger -.. % % blocks of code. - .. _tut-quality-control: 品質管理 ======== -高い品質のソフトウェアを開発するための一つのアプローチは、全ての関数に対し て開発と同時にテストを書き、開発の過程で頻繁にテストを走らせるというもので す。 - -.. % % One approach for developing high quality software is to write tests for -.. % % each function as it is developed and to run those tests frequently during -.. % % the development process. - -:mod:`doctest` モジュールでは、 -モジュールを検索して、プログラムの docstring に埋め込まれたテストの評価を行 うためのツールを提供しています。テストの作り方は単純で、 -典型的な呼び出し例とその結果を docstring にカット& ペーストするというもので す。この作業は、ユーザに使用例を与えるという意味で -ドキュメントの情報を増やすと同時に、ドキュメントに書かれている内容が正しい かどうか doctest モジュールが確認できるようにしています: - -.. % % The \ulink{\module{doctest}}{../lib/module-doctest.html} module provides -.. % % a tool for scanning a module and validating tests embedded in a program's -.. % % docstrings. Test construction is as simple as cutting-and-pasting a -.. % % typical call along with its results into the docstring. This improves -.. % % the documentation by providing the user with an example and it allows the -.. % % doctest module to make sure the code remains true to the documentation: +高い品質のソフトウェアを開発するための一つのアプローチは、各関数に対して開 発と +同時にテストを書き、開発の過程で頻繁にテストを走らせるというものです。 + +:mod:`doctest` モジュールでは、モジュールを検索してプログラムの docstring に +埋め込まれたテストの評価を行うためのツールを提供しています。 +テストの作り方は単純で、典型的な呼び出し例とその結果を docstring に +カット&ペーストするだけです。この作業は、ユーザに使用例を与えるという意味で +ドキュメントの情報を増やすと同時に、ドキュメントに書かれているコードが正し い +事を確認できるようになります。 :: @@ -368,14 +298,10 @@ return sum(values, 0.0) / len(values) import doctest - doctest.testmod() # automatically validate the embedded tests - -:mod:`unittest` モジュールは -:mod:`doctest` モジュールほど気楽に使えるものではありませんが、より網羅的な テストセットを別のファイルで管理することができます: - -.. % % The \ulink{\module{unittest}}{../lib/module-unittest.html} module is not -.. % % as effortless as the \module{doctest} module, but it allows a more -.. % % comprehensive set of tests to be maintained in a separate file: + doctest.testmod() # 組み込まれたテストを自動的に検証する。 + +:mod:`unittest` モジュールは :mod:`doctest` モジュールほど気楽に使えるもの では +ありませんが、より網羅的なテストセットを別のファイルで管理することができま す。 :: @@ -389,7 +315,7 @@ self.assertRaises(ZeroDivisionError, average, []) self.assertRaises(TypeError, average, 20, 30, 70) - unittest.main() # Calling from the command line invokes all tests + unittest.main() # コマンドラインから呼び出すと全てのテストを実行する。 .. _tut-batteries-included: @@ -397,50 +323,31 @@ バッテリー同梱 ============== -Python には "バッテリー同梱 (batteries included)" 哲学があります。この哲学 は、洗練され、安定した機能を持つ Python -の膨大なパッケージ群に如実に表れています。例えば: - -.. % % Python has a ``batteries included'' philosophy. This is best seen -.. % % through the sophisticated and robust capabilities of its larger -.. % % packages. For example: - -* The :mod:`xmlrpclib` および - :mod:`SimpleXMLRPCServer` - モジュールは、遠隔手続き呼び出し (remote procedure call) を全くたいしたこ とのない作業に変えてしまいます。モジュール名とは違い、XML - を扱うための直接的な知識は必要ありません。 - - .. % % \item The \ulink{\module{email}}{../lib/module-email.html} - .. % % package is a library for managing email messages, - .. % % including MIME and other RFC 2822-based message documents. Unlike - .. % % \module{smtplib} and \module{poplib} which actually send and receive - .. % % messages, the email package has a complete toolset for building or - .. % % decoding complex message structures (including attachments) - .. % % and for implementing internet encoding and header protocols. - -* The :mod:`email` パッケージは、MIME やその他の - RFC 2822 に基づくメッセージ文書を含む電子メイルメッセージを管理するための ライブラリです。実際にメッセージを送信したり受信したりする - :mod:`smtplib` や :mod:`poplib` と違って、email パッケージには (添付文書 を含む) - 複雑なメッセージ構造の構築やデコードを行ったり、インターネット標準のエン コードやヘッダプロトコルの実装を行ったりするための完全なツールセットを備えて います。 - - .. % % \item The \ulink{\module{xml.dom}}{../lib/module-xml.dom.html} and - .. % % \ulink{\module{xml.sax}}{../lib/module-xml.sax.html} packages provide - .. % % robust support for parsing this popular data interchange format. Likewise, - .. % % the \module{csv} module supports direct reads and writes in a common - .. % % database format. Together, these modules and packages greatly simplify - .. % % data interchange between python applications and other tools. - -* :mod:`xml.dom` および :mod:`xml.sax` - パッケージでは、一般的なデータ交換形式である XML - を解析するための頑健なサポートを提供しています。同様に、 :mod:`csv` モジ ュールでは、広く用いられている - データベース形式のデータを直接読み書きする機能をサポートしています。これ らのモジュールやパッケージは併用することで、Python アプリケーション - と他のツール群との間でのデータ交換を劇的に簡単化します。 - - .. % % \item Internationalization is supported by a number of modules including - .. % % \ulink{\module{gettext}}{../lib/module-gettext.html}, - .. % % \ulink{\module{locale}}{../lib/module-locale.html}, and the - .. % % \ulink{\module{codecs}}{../lib/module-codecs.html} package. - -* 国際化に関する機能は、 :mod:`gettext`, - :mod:`locale` および :mod:`codecs` パッケージといったモジュール群でサポー トされています。 +Python には "バッテリー同梱 (batteries included)" 哲学があります。この哲学 は、 +洗練され、安定した機能を持つ Python の膨大なパッケージ群に如実に表れていま す。 +例えば、 + + +* The :mod:`xmlrpclib` および :mod:`SimpleXMLRPCServer` モジュールは、 + 遠隔手続き呼び出し (remote procedure call) を全く大したことのない作業に + 変えてしまいます。モジュール名とは違い、XML を扱うための直接的な知識は + 必要ありません。 + +* The :mod:`email` パッケージは、MIME やその他の RFC 2822 に基づく + メッセージ文書を含む電子メールメッセージを管理するためのライブラリです。 + 実際にメッセージを送信したり受信したりする :mod:`smtplib` や :mod:`poplib` + と違って、email パッケージには (添付文書を含む) 複雑なメッセージ構造の構 築や + デコードを行ったり、インターネット標準のエンコードやヘッダプロトコルの実 装を + 行ったりするための完全なツールセットを備えています。 + +* :mod:`xml.dom` および :mod:`xml.sax` パッケージでは、一般的なデータ交換形 式 + である XML を解析するための頑健なサポートを提供しています。同様に、 + :mod:`csv` モジュールでは、広く用いられているデータベース形式のデータを + 直接読み書きする機能をサポートしています。これらのモジュールやパッケージ を + 利用することで、Python アプリケーションと他のツール群との間でのデータ交換 が + 劇的に簡単になります。 + +* 国際化に関する機能は、 :mod:`gettext`, :mod:`locale`, :mod:`codecs` + パッケージといったモジュール群でサポートされています。