16

__init__.pyファイルとその中に別のモジュールを含むメッセージフォルダ(パッケージ)がありますmessages_en.py__init__.pyインポートmessages_enすると機能__import__しますが、「ImportError:メッセージ_enという名前のモジュールがありません」で失敗します

import messages_en # it works
messages = __import__('messages_en') # it doesn't ?

私は「importx」は別の言い方だと思っていました__import__('x')

4

7 に答える 7

21

パスの問題である場合は、 (ドキュメントからの)level引数を使用する必要があります。

__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module

Level is used to determine whether to perform
absolute or relative imports.  -1 is the original strategy of attempting
both absolute and relative imports, 0 is absolute, a positive number
is the number of parent directories to search relative to the current module.
于 2009-06-29T11:49:01.627 に答える
20

globals 引数を追加するだけで十分です。

__import__('messages_en', globals=globals())

実際、ここでは のみ__name__が必要です:

__import__('messages_en', globals={"__name__": __name__})
于 2012-11-01T10:22:54.710 に答える
14

__import__import ステートメントによって呼び出される内部関数です。日常のコーディングでは、呼び出す必要がない (またはしたくない)__import__

Pythonのドキュメントから:

たとえば、このステートメントimport spamは、次のコードに似たバイトコードになります。

spam = __import__('spam', globals(), locals(), [], -1)

一方、ステートメントは次のようになりfrom spam.ham import eggs, sausage as sausます。

_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], -1)
eggs = _temp.eggs
saus = _temp.sausage

詳細: http://docs.python.org/library/functions.html

于 2009-06-29T11:46:41.710 に答える
4

modules ディレクトリを python パスに必ず追加してください。

パス (Python がモジュールとファイルを検索するために通過するディレクトリのリスト) は、sys モジュールの path 属性に格納されます。パスはリストであるため、append メソッドを使用して新しいディレクトリをパスに追加できます。

たとえば、ディレクトリ /home/me/mypy をパスに追加するには:

import sys
sys.path.append("/home/me/mypy") 
于 2010-05-09T20:07:42.990 に答える
2

あなたはこれを試すことができます:

messages == __import__('Foo.messages_en', fromlist=['messages_en'])
于 2009-06-29T11:53:31.727 に答える