pkgutil --- パッケージ拡張ユーティリティ

ソースコード: Lib/pkgutil.py


このモジュールはインポートシステムの、特にパッケージサポートに関するユーティリティです。

class pkgutil.ModuleInfo(module_finder, name, ispkg)

モジュールの概要情報を格納する namedtuple

バージョン 3.6 で追加.

pkgutil.extend_path(path, name)

パッケージを構成するモジュールの検索パスを拡張します。パッケージの __init__.py で次のように書くことを意図したものです:

from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)

For each directory on sys.path that has a subdirectory that matches the package name, add the subdirectory to the package's __path__. This is useful if one wants to distribute different parts of a single logical package as multiple directories.

同時に *.pkg* の部分が name 引数に指定された文字列に一致するファイルの検索もおこないます。この機能は import で始まる特別な行がないことを除き *.pth ファイルに似ています (site の項を参照)。 *.pkg は重複のチェックを除き、信頼できるものとして扱われます。 *.pkg ファイルの中に見つかったエントリはファイルシステム上に実在するか否かを問わず、そのまますべてパスに追加されます。(このような仕様です。)

入力パスがリストでない場合(フリーズされたパッケージのとき)は何もせずにリターンします。入力パスが変更されていなければ、アイテムを末尾に追加しただけのコピーを返します。

sys.path はシーケンスであることが前提になっています。 sys.path の要素の内、実在するディレクトリを指す文字列となっていないものは無視されます。ファイル名として使ったときにエラーが発生する sys.path の Unicode要素がある場合、この関数(os.path.isdir() を実行している行) で例外が発生する可能性があります。

class pkgutil.ImpImporter(dirname=None)

PEP 302 Finder that wraps Python's "classic" import algorithm.

If dirname is a string, a PEP 302 finder is created that searches that directory. If dirname is None, a PEP 302 finder is created that searches the current sys.path, plus any modules that are frozen or built-in.

Note that ImpImporter does not currently support being used by placement on sys.meta_path.

バージョン 3.3 で非推奨: This emulation is no longer needed, as the standard import mechanism is now fully PEP 302 compliant and available in importlib.

class pkgutil.ImpLoader(fullname, file, filename, etc)

Loader that wraps Python's "classic" import algorithm.

バージョン 3.3 で非推奨: This emulation is no longer needed, as the standard import mechanism is now fully PEP 302 compliant and available in importlib.

pkgutil.find_loader(fullname)

fullname に対するモジュール loader オブジェクトを取得します。

これは後方互換性のために提供している importlib.util.find_spec() へのラッパーで、そこでのほどんどの失敗を ImportError に変換し、完全な importlib.machinery.ModuleSpec を返す代わりにローダのみを返しています。

バージョン 3.3 で変更: パッケージ内部の PEP 302 エミュレーションに依存するのではなく直接的に importlib に基くように更新されました。

バージョン 3.4 で変更: PEP 451 ベースに更新されました。

pkgutil.get_importer(path_item)

指定された path_item に対する finder を取得します。

path hook により新しい finder が作成された場合は、それは sys.path_importer_cache にキャッシュされます。

キャッシュ (やその一部) は、 sys.path_hooks のリスキャンが必要になった場合は手動でクリアすることができます。

バージョン 3.3 で変更: パッケージ内部の PEP 302 エミュレーションに依存するのではなく直接的に importlib に基くように更新されました。

pkgutil.get_loader(module_or_name)

module_or_name に対する loader オブジェクトを取得します。

module か package が通常の import 機構によってアクセスできる場合、その機構の該当部分に対するラッパーを返します。モジュールが見つからなかったり import できない場合は None を返します。その名前のモジュールがまだ import されていない場合、そのモジュールを含むパッケージが(あれば)そのパッケージの __path__ を確立するために import されます。

バージョン 3.3 で変更: パッケージ内部の PEP 302 エミュレーションに依存するのではなく直接的に importlib に基くように更新されました。

バージョン 3.4 で変更: PEP 451 ベースに更新されました。

pkgutil.iter_importers(fullname='')

Yield finder objects for the given module name.

If fullname contains a '.', the finders will be for the package containing fullname, otherwise they will be all registered top level finders (i.e. those on both sys.meta_path and sys.path_hooks).

その名前のついたモジュールがパッケージ内に含まれている場合、この関数を実行した副作用としてそのパッケージが import されます。

モジュール名が指定されない場合は全てのトップレベルの finder が生成されます。

バージョン 3.3 で変更: パッケージ内部の PEP 302 エミュレーションに依存するのではなく直接的に importlib に基くように更新されました。

pkgutil.iter_modules(path=None, prefix='')

path を指定すればそのすべてのサブモジュールに対して、 pathNone なら sys.path のすべてのトップレベルモジュールに対して、ModuleInfo を yield します。

pathNone か、モジュールを検索する path のリストのどちらかでなければなりません。

prefix は出力の全てのモジュール名の頭に出力する文字列です。

注釈

これは iter_modules() メソッドを定義している finder に対してのみ動作します。このインターフェイスは非標準なので、モジュールは importlib.machinery.FileFinderzipimport.zipimporter の実装も提供します。

バージョン 3.3 で変更: パッケージ内部の PEP 302 エミュレーションに依存するのではなく直接的に importlib に基くように更新されました。

pkgutil.walk_packages(path=None, prefix='', onerror=None)

path を指定すれば再帰的にその中のモジュールすべてに対して、 pathNone ならばアクセスできるすべてのモジュールに対して、ModuleInfo を yield します。

pathNone か、モジュールを検索する path のリストのどちらかでなければなりません。

prefix は出力の全てのモジュール名の頭に出力する文字列です。

この関数は与えられた path 上の全ての パッケージ (全てのモジュール ではない) を、サブモジュールを検索するのに必要な __path__ 属性にアクセスするために import します。

onerror は、パッケージを import しようとしたときに何かの例外が発生した場合に、 1つの引数 (import しようとしていたパッケージの名前) で呼び出される関数です。 onerror 関数が提供されない場合、 ImportError は補足され無視されます。それ以外の全ての例外は伝播し、検索を停止させます。

例:

# list all modules python can access
walk_packages()

# list all submodules of ctypes
walk_packages(ctypes.__path__, ctypes.__name__ + '.')

注釈

これは iter_modules() メソッドを定義している finder に対してのみ動作します。このインターフェイスは非標準なので、モジュールは importlib.machinery.FileFinderzipimport.zipimporter の実装も提供します。

バージョン 3.3 で変更: パッケージ内部の PEP 302 エミュレーションに依存するのではなく直接的に importlib に基くように更新されました。

pkgutil.get_data(package, resource)

パッケージからリソースを取得します。

この関数は loader get_data API のラッパーです。 package 引数は標準的なモジュール形式 (foo.bar) のパッケージ名でなければなりません。 resource 引数は / をパス区切りに使った相対ファイル名の形式です。親ディレクトリを .. としたり、ルートからの (/ で始まる) 名前を使うことはできません。

この関数が返すのは指定されたリソースの内容であるバイナリ文字列です。

ファイルシステム中に位置するパッケージで既にインポートされているものに対しては、次と大体同じです:

d = os.path.dirname(sys.modules[package].__file__)
data = open(os.path.join(d, resource), 'rb').read()

If the package cannot be located or loaded, or it uses a loader which does not support get_data, then None is returned. In particular, the loader for namespace packages does not support get_data.

pkgutil.resolve_name(name)

Resolve a name to an object.

This functionality is used in numerous places in the standard library (see bpo-12915) - and equivalent functionality is also in widely used third-party packages such as setuptools, Django and Pyramid.

It is expected that name will be a string in one of the following formats, where W is shorthand for a valid Python identifier and dot stands for a literal period in these pseudo-regexes:

  • W(.W)*

  • W(.W)*:(W(.W)*)?

The first form is intended for backward compatibility only. It assumes that some part of the dotted name is a package, and the rest is an object somewhere within that package, possibly nested inside other objects. Because the place where the package stops and the object hierarchy starts can't be inferred by inspection, repeated attempts to import must be done with this form.

In the second form, the caller makes the division point clear through the provision of a single colon: the dotted name to the left of the colon is a package to be imported, and the dotted name to the right is the object hierarchy within that package. Only one import is needed in this form. If it ends with the colon, then a module object is returned.

The function will return an object (which might be a module), or raise one of the following exceptions:

ValueError -- if name isn't in a recognised format.

ImportError -- if an import failed when it shouldn't have.

AttributeError -- If a failure occurred when traversing the object hierarchy within the imported package to get to the desired object.

バージョン 3.9 で追加.