PyQT アプリケーションを開発しています。このアプリケーションは、データベースからいくつかのデータをロードし、これらのデータに対してさまざまな分析を行うことができます。これはすべて機能します。しかし、分析は非常に複雑になる可能性があり、ユーザーが唯一ではないため、ユーザー定義のスクリプトを使用してシステムを開発する必要がありました。基本的に、ユーザーが独自の小さな Python スクリプト (関数付き) をプログラムできるテキスト エディターがあります。次に、ユーザーは、ファイルをモジュールとして (アプリケーション内で) ロードすることにより、スクリプトを保存または実行できます。
ここに、私のアプリケーションの簡略化されたバージョンがあります。
アプリケーションのコアは My_apps.py にあり、プラグインは同じフォルダー、つまり Plugin_A.py にあります。
これは My_apps.py のコードです:
import sys,os
class Analysis(object):
def __init__(self):
print "I'm the core of the application, I do some analysis etc..."
def Analyze_Stuff(self):
self.Amplitudes_1=[1,2,3,1,2,3]
class Plugins(object):
def __init__(self):
newpath = "C:\Users\Antoine.Valera.NEUROSECRETION\Desktop\Model" #where the file is
sys.path.append(newpath)
Plugin_List=[]
for module in os.listdir(newpath):
if os.path.splitext(module)[1] == ".py":
module=module.replace(".py","")
Plugin_List.append(module)
for plugin in Plugin_List:
a=__import__(plugin)
setattr(self,plugin,a)
def Execute_a_Plugin(self):
Plugins.Plugin_A.External_Function(self)
if __name__ == "__main__":
Analysis=Analysis()
Plugins=Plugins()
Plugins.Execute_a_Plugin()
これは Plugin_A.py のコードの例です
def External_Function(self):
Analysis.Analyze_Stuff()
print Analysis.Amplitudes_1
なぜ私は得るのですか:
Traceback (most recent call last):
File "C:\Users\Antoine.Valera.NEUROSECRETION\Desktop\Model\My_Apps.py", line 46, in <module>
Plugins.Execute_a_Plugin()
File "C:\Users\Antoine.Valera.NEUROSECRETION\Desktop\Model\My_Apps.py", line 37, in Execute_a_Plugin
Plugins.Plugin_A.External_Function(self)
File "C:\Users\Antoine.Valera.NEUROSECRETION\Desktop\Model\Plugin_A.py", line 8, in External_Function
Analysis.Analyze_Stuff()
NameError: global name 'Analysis' is not defined
しかし、次の行の代わりに2行を追加するとPlugins.Execute_a_Plugin()
Analysis.Analyze_Stuff()
print Analysis.Amplitudes_1
その後、動作します。
動的に読み込まれるすべてのプラグインに、Analysis に既に存在する変数/オブジェクトを使用する必要があることをどのように示すことができますか? プラグイン内から Analysis.Amplitudes_1 を出力できないのはなぜですか?
ありがとうございました!!