def GetModule(filename): """ Give module object from python file path. Warning, the name of python_file must be the same of the classe name. """ dir_name = os.path.dirname(filename) ### if python_file is ...../toto.amd/Atomic_Model.py, then the parent dir is zipfile. if zipfile.is_zipfile(dir_name): zf = ZipManager.Zip(dir_name) return zf.GetModule() elif zipfile.is_zipfile(filename): zf = ZipManager.Zip(filename) return zf.GetModule() ### if python file is on the web ! elif filename.startswith(('http', 'https')): net = NetManager.Net(filename) return net.GetModule() ### pure python file else: module_name = os.path.basename(filename).split('.py')[0] # find and load module try: f, fn, description = imp.find_module(module_name, [dir_name]) module = imp.load_module(module_name, f, fn, description) f.close() return module except Exception, info: return sys.exc_info()
def Load(filename, label): """ Load AMD from constructor. """ assert (filename.endswith('.amd')) python_path = os.path.join(filename, ZipManager.getPythonModelFileName(filename)) cls = GetClass(python_path) m = AMDComponent.BlockModelAdapter(cls, label) load_file_result = m.LoadFile(filename) if isinstance(load_file_result, Exception): wx.MessageBox( _('Error loading %s model : %s ' % (label, load_file_result)), _('Error'), wx.OK | wx.ICON_ERROR) return None else: ### mandatory due to the LoadFile call before m.label = label return m
def __init__(self, **kwargs): """ Constructor. """ self.model = kwargs.pop('model') wx.Frame.__init__(self, **kwargs) ### plugin panel self.pluginPanel = PluginsPanel(self) ### two panel into plugin panel rpanel = self.pluginPanel.GetRightPanel() lpanel = self.pluginPanel.GetLeftPanel() ### checklist to insert in right panel self.CheckList = BlockPluginsList(rpanel) wx.CallAfter(self.CheckList.Populate, self.model) ### Buttons for insert or delete plugins self.addBtn = wx.Button(lpanel, wx.ID_ADD, size=(140, -1)) self.delBtn = wx.Button(lpanel, wx.ID_DELETE, size=(140, -1)) self.editBtn = wx.Button(lpanel, wx.ID_EDIT, size=(140, -1)) self.updateBtn = wx.Button(lpanel, wx.ID_APPLY, size=(140, -1)) self.addBtn.SetToolTipString(_("Add new plugins")) self.delBtn.SetToolTipString(_("Delete all existing plugins")) self.editBtn.SetToolTipString(_("Edit plugin file")) self.updateBtn.SetToolTipString(_("Update plugin list")) ### add widget to plugin panel self.pluginPanel.SetPluginsList(self.CheckList) self.pluginPanel.AddWidget(3, self.addBtn) self.pluginPanel.AddWidget(4, self.editBtn) self.pluginPanel.AddWidget(5, self.updateBtn) self.pluginPanel.AddWidget(6, self.delBtn) #### zipfile (amd or cmd) try: self.zf = ZipManager.Zip(self.model.model_path) cond = ZipManager.Zip.HasPlugin(self.model.model_path) except AttributeError: sys.stdout.write(_('PluginsGUI in mode alone.\n')) cond = False ### enable del, add and udpate buttons self.delBtn.Enable(cond) self.addBtn.Enable(not cond) self.updateBtn.Enable(False) self.Bind(wx.EVT_BUTTON, self.OnAdd, id=self.addBtn.GetId()) self.Bind(wx.EVT_BUTTON, self.OnDelete, id=self.delBtn.GetId()) self.Bind(wx.EVT_BUTTON, self.OnEdit, id=self.editBtn.GetId()) self.Bind(wx.EVT_BUTTON, self.OnRefresh, id=self.updateBtn.GetId()) self.CenterOnParent(wx.BOTH) self.Layout()
def CreateTestsFiles(self): devsPath = os.path.dirname(self.python_path) name = os.path.splitext(os.path.basename(self.python_path))[0] zf = ZipManager.Zip(devsPath) feat, steps, env = self.CreateFeature(), self.CreateSteps( ), Testable.CreateEnv() zf.Update([ os.path.join('BDD', feat), os.path.join('BDD', steps), os.path.join('BDD', env) ]) if os.path.exists(feat): os.remove(feat) if os.path.exists(steps): os.remove(steps) if os.path.exists(env): os.remove(env)
def Load(filename, label): """ Load AMD from constructor. """ assert (filename.endswith('.amd')) python_path = os.path.join(filename, ZipManager.getPythonModelFileName(filename)) cls = GetClass(python_path) m = AMDComponent.BlockModelAdapter(cls, label) load_file_result = m.LoadFile(filename) if isinstance(load_file_result, Exception): wx.MessageBox(_('Error loading %s model : %s '%(label, load_file_result)), _('Error'), wx.OK | wx.ICON_ERROR) return None else: ### mandatory due to the LoadFile call before m.label = label return m
def recompile(modulename): """ recompile module from modulename """ ### modulename is file type if os.path.exists(modulename): zf = ZipManager.Zip(modulename) return zf.Recompile() else: ### first, see if the module can be imported at all... tmp = __import__(modulename, globals(), locals(), fromlist=[modulename.split('.')[-1]]) ### Use the imported module to determine its actual path pycfile = tmp.__file__ modulepath = string.replace(pycfile, ".pyc", ".py") ### Try to open the specified module as a file code = open(modulepath, 'rU').read() ### see if the file we opened can compile. If not, return the error that it gives. ### if compile() fails, the module will not be replaced. try: compile(code, modulename, "exec") except: return "Error in compilation: " + str(sys.exc_info()[0]) + "\r\n" + Utilities.listf(format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) else: ### Ok, it compiled. But will it execute without error? try: execfile(modulepath) except Exception: #return "Error '%s' happened on line %d" % (info[0], info[1][1]) return "Error in execution: " + str(sys.exc_info()[0]) + "\r\n" + Utilities.listf(format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) else: ### at this point, the code both compiled and ran without error. Load it up ### replacing the original code. return reload(sys.modules[modulename])
def OnItemEdit(self, evt): item = self.GetSelection() path = self.GetItemPyData(item) ### virtual DEVS component just for edition devscomp = Components.DEVSComponent() ### path depends on the nature of droped component ### if pure python path if path.endswith('.py'): devscomp.setDEVSPythonPath(path) ### if devsimpy model elif zipfile.is_zipfile(path): #zf = ZipManager.Zip(path) devscomp.setDEVSPythonPath( os.path.join(path, ZipManager.getPythonModelFileName(path))) devscomp.model_path = path else: sys.stdout.write( _('The code of this type of model is not editable')) return ### call frame editor Components.DEVSComponent.OnEditor(devscomp, evt)
def GetTempTests(self, global_env=None): if not global_env: global_env = False ### Useful vars definition----------------------------------------------------------------- model_path = os.path.dirname(self.python_path) basename = os.path.basename(self.python_path) name = os.path.splitext(basename)[0] tests_files = ZipManager.Zip.GetTests(model_path) ### --------------------------------------------------------------------------------------- ### Folder hierarchy construction---------------------------------------------------------- feat_dir = os.path.join(gettempdir(), "features") steps_dir = os.path.join(feat_dir, "steps") if not os.path.exists(feat_dir): os.mkdir(feat_dir) if not os.path.exists(steps_dir): os.mkdir(steps_dir) ### --------------------------------------------------------------------------------------- ### AMD unzip------------------------------------------------------------------------------ amd_dir = os.path.join(gettempdir(), "AtomicDEVS") if not os.path.exists(amd_dir): os.mkdir(amd_dir) ### --------------------------------------------------------------------------------------- ### Tests code retriever------------------------------------------------------------------- importer = zipfile.ZipFile(model_path) feat_name = filter(lambda t: t.endswith('.feature'), tests_files)[0] featInfo = importer.getinfo(feat_name) feat_code = importer.read(featInfo) steps_name = filter(lambda t: t.endswith('steps.py'), tests_files)[0] stepsInfo = importer.getinfo(steps_name) steps_code = importer.read(stepsInfo) if not global_env: environment_name = filter(lambda t: t.endswith('environment.py'), tests_files)[0] envInfo = importer.getinfo(environment_name) env_code = importer.read(envInfo) else: environment_name = os.path.join(gettempdir(), 'environment.py') with open(environment_name, 'r+') as global_env_code: env_code = global_env_code.read() importer.close() ### --------------------------------------------------------------------------------------- ### AMD code retriever--------------------------------------------------------------------- importer = zipfile.ZipFile(model_path) # amd_name = filter(lambda t: t.endswith('%s.py'%name), importer.namelist())[0] amd_name = ZipManager.getPythonModelFileName(model_path) amd_info = importer.getinfo(amd_name) amd_code = importer.read(amd_info) ### --------------------------------------------------------------------------------------- ### Tests files creation in temporary directory-------------------------------------------- tempFeature = os.path.join(feat_dir, "%s.feature" % name) tempEnv = os.path.join(feat_dir, "environment.py") tempSteps = os.path.join(steps_dir, "%s_steps.py"%name) tempAMD = os.path.join(amd_dir, amd_name) with open(tempFeature, 'w+') as feat: feat.write(feat_code) with open(tempSteps, 'w+') as steps: steps.write(steps_code) with open(tempEnv, 'w+') as env: env.write(env_code) with open(tempAMD, 'w+') as AMD: AMD.write(amd_code) ### --------------------------------------------------------------------------------------- return tempFeature, tempSteps, tempEnv
fn = 'DEVSimPyModel.dat' ### dump attributes in fn file cPickle.dump(obj=PickledCollection(obj_dumped), file=open(fn, "wb"), protocol=0) except Exception, info: sys.stderr.write(_("Problem saving (during the dump): %s -- %s\n") % (str(fileName), info)) return False else: try: zf = ZipManager.Zip(fileName) ### create or update fileName if os.path.exists(fileName): zf.Update(replace_files=[fn, python_path, image_path]) else: zf.Create(add_files=[fn, python_path, image_path]) os.remove(fn) ## chemin absolu du repertoir contenant le fichier a exporter (str() pour eviter l'unicode) newExportPath = str(os.path.dirname(fileName)) mainW = Utilities.getTopLevelWindow() ### si export dans un repertoir local on insert le chemin dans le fichier de config if not os.path.basename(DOMAIN_PATH) in newExportPath.split(os.sep):
def GetTempTests(self, global_env=None): if not global_env: global_env = False ### Useful vars definition----------------------------------------------------------------- model_path = os.path.dirname(self.python_path) basename = os.path.basename(self.python_path) name = os.path.splitext(basename)[0] tests_files = ZipManager.Zip.GetTests(model_path) ### --------------------------------------------------------------------------------------- ### Folder hierarchy construction---------------------------------------------------------- feat_dir = os.path.join(gettempdir(), "features") steps_dir = os.path.join(feat_dir, "steps") if not os.path.exists(feat_dir): os.mkdir(feat_dir) if not os.path.exists(steps_dir): os.mkdir(steps_dir) ### --------------------------------------------------------------------------------------- ### AMD unzip------------------------------------------------------------------------------ amd_dir = os.path.join(gettempdir(), "AtomicDEVS") if not os.path.exists(amd_dir): os.mkdir(amd_dir) ### --------------------------------------------------------------------------------------- ### Tests code retriever------------------------------------------------------------------- importer = zipfile.ZipFile(model_path) feat_name = filter(lambda t: t.endswith('.feature'), tests_files)[0] featInfo = importer.getinfo(feat_name) feat_code = importer.read(featInfo) steps_name = filter(lambda t: t.endswith('steps.py'), tests_files)[0] stepsInfo = importer.getinfo(steps_name) steps_code = importer.read(stepsInfo) if not global_env: environment_name = filter(lambda t: t.endswith('environment.py'), tests_files)[0] envInfo = importer.getinfo(environment_name) env_code = importer.read(envInfo) else: environment_name = os.path.join(gettempdir(), 'environment.py') with open(environment_name, 'r+') as global_env_code: env_code = global_env_code.read() importer.close() ### --------------------------------------------------------------------------------------- ### AMD code retriever--------------------------------------------------------------------- importer = zipfile.ZipFile(model_path) # amd_name = filter(lambda t: t.endswith('%s.py'%name), importer.namelist())[0] amd_name = ZipManager.getPythonModelFileName(model_path) amd_info = importer.getinfo(amd_name) amd_code = importer.read(amd_info) ### --------------------------------------------------------------------------------------- ### Tests files creation in temporary directory-------------------------------------------- tempFeature = os.path.join(feat_dir, "%s.feature" % name) tempEnv = os.path.join(feat_dir, "environment.py") tempSteps = os.path.join(steps_dir, "%s_steps.py" % name) tempAMD = os.path.join(amd_dir, amd_name) with open(tempFeature, 'w+') as feat: feat.write(feat_code) with open(tempSteps, 'w+') as steps: steps.write(steps_code) with open(tempEnv, 'w+') as env: env.write(env_code) with open(tempAMD, 'w+') as AMD: AMD.write(amd_code) ### --------------------------------------------------------------------------------------- return tempFeature, tempSteps, tempEnv
def InsertNewDomain(self, dName, parent, L=None): """ Recurcive function that insert new Domain on library panel. """ if not L: L = [] ### au depard seulement pour le parent de plus haut niveau (comme PowerSystem) if dName not in self.ItemDico.keys(): label = os.path.basename( dName) if not dName.startswith('http') else filter( lambda a: a != '', dName.split('/'))[-1] id = self.InsertItemBefore(parent, 0, label) self.SetItemImage(id, self.fldridx, wx.TreeItemIcon_Normal) self.SetItemImage(id, self.fldropenidx, wx.TreeItemIcon_Expanded) self.SetItemBold(id) self.ItemDico.update({dName: id}) self.SetPyData(id, dName) ### fin de la recursion if not L: return else: item = L.pop(0) assert not isinstance(item, unicode), _("Warning unicode item !") ### element a faire remonter dans la liste D = [] ### si le fils est un modele construit dans DEVSimPy if isinstance(item, str): ### le parent est recupere dans le Dico parent = self.ItemDico[dName] assert parent is not None ### path correspondant au parent parentPath = self.GetPyData(parent) ### remplacement des espaces item = item.strip() come_from_net = parentPath.startswith('http') ### suppression de l'extention su .cmd (model atomic lue a partir de __init__ donc pas d'extention) if item.endswith('.cmd'): ### gestion de l'importation de module (.py) associe au .cmd si le fichier .py n'a jamais ete decompressse (pour edition par exemple) if not come_from_net: path = os.path.join(parentPath, item) zf = ZipManager.Zip(path) module = zf.GetModule() image_file = zf.GetImage() else: path = parentPath + '/' + item + '.py' module = load_module_from_net(path) ### check error error = isinstance(module, Exception) ### change icon depending on the error and the presence of image in amd if error: img = self.not_importedidx elif image_file is not None: img = self.il.Add(image_file.ConvertToBitmap()) else: img = self.coupledidx ### insertion dans le tree id = self.InsertItemBefore(parent, 0, os.path.splitext(item)[0], img, img) self.SetPyData(id, path) elif item.endswith('.amd'): ### gestion de l'importation de module (.py) associe au .amd si le fichier .py n'a jamais ete decompressse (pour edition par exemple) if not come_from_net: path = os.path.join(parentPath, item) zf = ZipManager.Zip(path) module = zf.GetModule() image_file = zf.GetImage() else: path = parentPath + '/' + item + '.py' module = load_module_from_net(path) ### check error error = isinstance(module, Exception) ### change icon depending on the error and the presence of image in amd if error: img = self.not_importedidx elif image_file is not None: img = self.il.Add(image_file.ConvertToBitmap()) else: img = self.atomicidx ### insertion dans le tree id = self.InsertItemBefore(parent, 0, os.path.splitext(item)[0], img, img) self.SetPyData(id, path) else: path = os.path.join( parentPath, item + '.py') if not parentPath.startswith( 'http') else parentPath + '/' + item + '.py' info = Container.CheckClass(path) error = isinstance(info, tuple) img = self.not_importedidx if error else self.pythonfileidx ### insertion dans le tree id = self.InsertItemBefore(parent, 0, item, img, img) self.SetPyData(id, path) ### error info back propagation if error: while parent: self.SetItemImage(parent, self.not_importedidx, wx.TreeItemIcon_Normal) ### next parent item parent = self.GetItemParent(parent) ### insertion des donnees dans l'item et gestion du ItemDico self.ItemDico.update({os.path.join( parentPath, item, ): id}) ### si le fils est un sous repertoire contenant au moins un fichier (all dans __init__.py different de []) elif isinstance(item, dict) and item.values() != [[]]: ### nom a inserer dans l'arbe dName = os.path.basename(item.keys()[0]) ### nouveau parent parent = self.ItemDico[os.path.dirname( item.keys()[0])] if not dName.startswith( 'http') else self.ItemDico[item.keys()[0].replace( '/' + dName, '')] assert (parent is not None) ### insertion de fName sous parent id = self.InsertItemBefore(parent, 0, dName) self.SetItemImage(id, self.fldridx, wx.TreeItemIcon_Normal) self.SetItemImage(id, self.fldropenidx, wx.TreeItemIcon_Expanded) ### stockage du parent avec pour cle le chemin complet avec extention (pour l'import du moule dans le Dnd) self.ItemDico.update({item.keys()[0]: id}) self.SetPyData(id, item.keys()[0]) ### pour les fils du sous domain for elem in item.values()[0]: # si elem simple (modele couple ou atomic) if isinstance(elem, str): ### remplacement des espaces elem = elem.strip() #replace(' ','') ### parent provisoir p = self.ItemDico[item.keys()[0]] assert (p is not None) come_from_net = item.keys()[0].startswith('http') ### si model atomic if elem.endswith('.cmd'): ### gestion de l'importation de module (.py) associe au .amd si le fichier .py n'a jamais ete decompressse (pour edition par exemple) if not come_from_net: path = os.path.join(item.keys()[0], elem) zf = ZipManager.Zip(path) module = zf.GetModule() image_file = zf.GetImage() else: path = item.keys()[0] + '/' + elem + '.py' moduel = load_module_from_net(path) ### check error error = isinstance(module, Exception) ### change icon depending on the error and the presence of image in amd if error: img = self.not_importedidx elif image_file is not None: img = self.il.Add(image_file.ConvertToBitmap()) else: img = self.coupledidx ### insertion dans le tree id = self.InsertItemBefore( p, 0, os.path.splitext(elem)[0], img, img) self.SetPyData(id, path) elif elem.endswith('.amd'): ### gestion de l'importation de module (.py) associe au .amd si le fichier .py n'a jamais ete decompressse (pour edition par exemple) if not come_from_net: path = os.path.join(item.keys()[0], elem) zf = ZipManager.Zip(path) module = zf.GetModule() image_file = zf.GetImage() else: path = item.keys()[0] + '/' + elem + '.py' moduel = load_module_from_net(path) ### check error error = isinstance(module, Exception) ### change icon depending on the error and the presence of image in amd if error: img = self.not_importedidx elif image_file is not None: img = self.il.Add(image_file.ConvertToBitmap()) else: img = self.atomicidx ### insertion dans le tree id = self.InsertItemBefore( p, 0, os.path.splitext(elem)[0], img, img) self.SetPyData(id, path) else: path = os.path.join( item.keys()[0], elem + '.py') if not item.keys()[0].startswith( 'http' ) else item.keys()[0] + '/' + elem + '.py' info = Container.CheckClass(path) error = isinstance(info, tuple) img = self.not_importedidx if error else self.pythonfileidx ### insertion dans le tree id = self.InsertItemBefore(p, 0, elem, img, img) self.SetPyData(id, path) ### error info back propagation if error: ### insert error to the doc field while p: self.SetItemImage(p, self.not_importedidx, wx.TreeItemIcon_Normal) ### next parent item p = self.GetItemParent(p) self.ItemDico.update({ os.path.join(item.keys()[0], os.path.splitext(elem)[0]): id }) else: ### pour faire remonter l'info dans la liste D.append(elem) ### mise a jour avec le nom complet dName = item.keys()[0] ### for spash screen try: ### format the string depending the nature of the item if isinstance(item, dict): item = "%s from %s" % ( os.path.basename(item.keys()[0]), os.path.basename(os.path.dirname(item.keys()[0]))) else: item = "%s from %s" % (item, os.path.basename(dName)) pub.sendMessage('object.added', 'Loading %s domain...' % item) except: pass ### gestion de la recursion if D: return self.InsertNewDomain(dName, parent, L + D) else: return self.InsertNewDomain(dName, parent, L)