質問

私は動的に私が作成したモジュールをロードしようとしています。

今これが正常に動作します。

import structures.index

しかし、私はそれを動的にインポートすることで同じことをしようとした場合、それは失敗します。

struct = __import__("structures.index")

供給エラーがあります:

Error ('No module named structures.index',)

任意のアイデアなぜですか?

<時間>

編集:フルスコープ(?作品のそれの一種)を使用する場合:

struct = __import__("neoform.structures.index")

これはすべてのエラーをスローしません、しかし、それは代わりに「neoform」モジュールをロードしています、インデックスモジュールをロードしていません。

"構造体" の結果は、次のとおりです。

<module 'neoform' from '/neoform/__init__.py'>

また、サイドの問題として、どのように私は、動的にロードされたモジュール内のクラスをインスタンス化することができますか? (すべてのモジュールが共通のクラス名を含むと仮定して)。

編集:ソリューション:(感謝coonj&リック)これは働いていた何ことになりました。わからない理由を(まだ)が、fromlistは 『(ファイルは、それだけで1クラスを持っていたことを考えると奇妙な、)の値として「私は手紙を入れたときに、それが働いていたので、どうやら何でも、』何かしなければならなかった。

def get_struct_module(self, name):
    try:
        return = __import__("neoform.structures." + name, fromlist='*')
    except ImportError, e:
        self.out.add("Could not load struct: neoform.structure." + name + "\n\n" + "Error " + str(e.args))
役に立ちましたか?

解決

私は手段を「それが失敗し、」何か分からないので、私は__import__('structures.index')が、実際には、動作するはずですが、それは現在のスコープ内のモジュール名を割り当てていないことだけ言及します。それを行う(その後、動的にインポートされたモジュール内のクラスを使用)するには、使用する必要があります:

structures = __import__('structures.index')
structures.index.SomeClass(...)

__import__に関する詳細はこちらの用意されています。

編集:(質問の編集に基づく)

neoform.structures.indexをインポートし、indexモジュールを返すには、次の操作を行います。

structures = __import__('neoform.structures.index', 
                        fromlist=['does not in fact matter what goes here!'])

はパッケージ名packagesのリストを持っている場合、あなたは彼らのindexモジュールをインポートし、次のコードを使用して、それぞれにいくつかのMyClassクラスをインスタンス化することができますのでます:

modules = [ __import__('neoform.%s.index' % pkg, fromlist=['a']) 
            for pkg in packages ]
objects = [ m.MyClass() for m in modules ]

他のヒント

のサブモジュールをインポートするには、例えば、Foをfromlist
__import__()の引数に相当し、それらを指定する必要があります

import structures.index

です。

structures = __import__('structures', fromlist=['index'])

マップでこれを行うには、

...もう少しトリッキーです
import mod1.index
import mod2.index
import mod3.index
これらの輸入品のため、あなたは、各モジュールからのindexサブモジュールを取得するには、新しい関数を定義したいと思う。

def getIndexMods(mod_names):
  mod_list = map(lambda x: __import__(x, fromlist='index'))
  index_mods = [mod.index for mod in mod_list]
  return index_mods

さて、あなたはすべての索引モジュールへの参照を取得するには、この操作を行うことができます:

index_mods = getIndexMods(['mod1', 'mod2', 'mod3'])

あなたが「インデックス」という名前されていないサブモジュールをつかむしたい場合はまた、あなたがこれを行うことができます:

mod1, mod2, mod3 = map(lambda x,y: __import__(x, fromlist=y), 
  ['mod1', 'mod2', 'mod3'], ['index1', 'index2', 'index3'])

このヘルパーメソッドとの完全な範囲( "neoform.structures.index")を使用します。

def import_module(name):
    mod = __import__(name)
    components = name.split('.')
    for comp in components[1:]:
        mod = getattr(mod, comp)
    return mod

module = import_module("neoform.structures.index")
# do stuff with module
ここで

Javaプログラマが、私はあなたが必要だと思う IMPモジュール

>>> import imp
>>> fm = imp.find_module('index', ['./structures']) # for submodule
>>> mymod = imp.load_module('structures.index', *fm)
>>> mymod
<module 'structures.index' from './structures/index.pyc'>
>>> x = mymod.insideIndex()
Initialising index class...

出来上がり!

なぜ地球上であなたが代わる

import structures.index

タグ付き
map(__import__, ["structures.index"])

最初のものは、(a)は動作し、(b)は、の動的及び(c)は直接サポートされています。より複雑な何かを簡単に変更、プレーンテキストのソースを交換するための可能な何を使用する場合がありますか?

要するに:これをしません。これは、任意の値を持っていません。

<時間>

編集

「私は、データベースからのインポートを得ている」賢明な高貴な努力ですが、まだありません。どのようなコードブロックは、それらの輸入に依存して?その全体のコードブロック - 輸入、すべてが - あなたが実行したいものです。その全体のコードブロック - 輸入、ステートメントおよびすべて - 昔ながらのPythonモジュールのファイルである必要があります。

ファイル・システムからのコードのブロックをインポートします。あなたがデータベースを使用したいもの - どのファイル、ファイルの作成者を特定するためにデータベースを使用します。しかし、単純にインポートし、モジュールにできるだけ簡単な方法を実行します。

ここでは本当に後半のポスト。しかし、私はGoogleでこの質問を探していました。私はいくつかの試行錯誤をしました。このスニペットが役立つかどうかわからないが、ここにあります。フラスコサイトのためにそれを使用します。

modules = ['frontend', 'admin']
for module in modules:
    mod = __init__('controllers.%s' % module, fromlist=[module])
    app.register_blueprint(mod.blueprint_mod)


# or
from importlib import import_module
modules = ['frontend', 'admin']
for module in modules:
    mod = import_module('controllers.%s' % module)
    app.regitster_blueprint(mod.blueprint_mod)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top