저는 PyQT 응용 프로그램을 개발 중입니다. 이 응용 프로그램은 데이터베이스에서 일부 데이터를로드 한 다음 이러한 데이터에 대해 다양한 분석을 수행 할 수 있습니다. 이 모든 것이 작동합니다. 그러나 분석이 복잡 할 수 있고 유일한 사용자가 아니기 때문에 사용자 정의 스크립트로 시스템을 개발해야했습니다. 기본적으로 사용자가 자신의 작은 파이썬 스크립트 (함수 포함)를 프로그래밍 할 수있는 텍스트 편집기가 있습니다. 그런 다음 사용자는 스크립트를 저장하거나 응용 프로그램 내에서 모듈로 파일을로드하여 스크립트를 실행할 수 있습니다.전체 응용 프로그램에서 변수/개체에 어떻게 액세스합니까?
내 응용 프로그램의 단순화 된 버전이 있습니다. 여기
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
이이 My_apps.py의 코드
응용 프로그램의 핵심은 My_apps.py 에 있고 플러그인이 같은 폴더에 위치 Plugin_A.py
def External_Function(self):
Analysis.Analyze_Stuff()
print Analysis.Amplitudes_1
의 코드의 예입니다 왜 내가받을 수 있나요 :
그때 대신Analysis.Analyze_Stuff()
print Analysis.Amplitudes_1
Plugins.Execute_a_Plugin()
의 선 다음 두 줄을 추가하는 경우
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
하지만, 그것을 작동합니다.
동적으로로드 된 모든 플러그인에 Analysis에 이미있는 변수/개체를 사용해야한다는 것을 어떻게 나타낼 수 있습니까? 왜 플러그인 내에서 Analysis.Amplitudes_1를 인쇄 할 수 없습니까?
감사합니다.
좋습니다.이 솔루션은 잘 작동합니다! 어쩌면 마지막 지점 일 수도 있습니다. 신청서에는 6 가지 중요한 수업이 있습니다. 개별적으로 모두 이름을 지정하지 않고 플러그인 기능에서 자동으로 전달하는 쉬운 방법이 있습니까? (나는 그들을 kargs 또는 ** kwargs에 포함시킬 수있다). 나는 ARG = [분석, Class2, Class3, Class4, Class5, Class6]을 시도한 다음 'Execute_a_Plugin (self) : 'plugins.Plugin_A.External_Function (self, Analysis, Class2, Class3, Class4, Class5, Class6))' 'plugins.Plugin_A.External_Function (self, * ARG)'를 호출 할 수 있으며
을 사용할 수 있습니다. 그러나 함수 정의에 * ARG가있는 것을 선호합니다. – Vantoine
@Vantoine. 다른 모든 클래스 인스턴스를 특성으로 갖는 컨테이너 클래스를 가질 수 있으며 컨테이너를 플러그인에 전달할 수 있습니다. – ekhumoro
어때? (그것은 효과가 있었지만 가장 깨끗한 방법은 아니 었습니다 ...) : 프로그램 시작 부분에 Class_List = [Navigate, Requete, Analysis, Main, Infos, Mapping]을 클래스에 추가합니다. setattr 플러그인을로드 할 때'setattr (sys.modules [__ name __], plugin, __ import __ (plugin))'),로드 된 플러그인의 이름 인 plugin을 사용합니다. – Vantoine