diff --git a/Components.py b/Components.py index 1c9ea03f..1cf51fda 100644 --- a/Components.py +++ b/Components.py @@ -24,7 +24,6 @@ import os import sys -import imp import inspect import zipfile import zipimport @@ -40,7 +39,6 @@ from tempfile import gettempdir - if builtins.__dict__.get('GUI_FLAG',True): import wx @@ -50,8 +48,6 @@ import ZipManager -#from DomainInterface.DomainBehavior import DomainBehavior -#from DomainInterface.DomainStructure import DomainStructure from ReloadModule import recompile from Utilities import GetActiveWindow, path_to_module, install_and_import, printOnStatusBar from NetManager import Net @@ -743,13 +739,13 @@ def GetModule(filename): # find and load module #try: - #name, ext = os.path.splitext(module_name) - #pkg = '.'.join(modulename.split('.')[0:-1]) - #module = importlib.import_module(name, package=pkg) + name, ext = os.path.splitext(module_name) + pkg = '.'.join(module_name.split('.')[0:-1]) + module = importlib.import_module(name, package=pkg) - f, fn, description = imp.find_module(module_name, [dir_name]) - module = imp.load_module(module_name, f, fn, description) - f.close() + #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 as info: @@ -787,7 +783,7 @@ def GetBlock(filename, label): def CreateBlock(*argv, **kwargs): """ Create Block from python_file and other info coming from wizard. """ - + from Container import iPort, oPort, MsgBoxError ### import are here because the simulator (PyDEVS or PyPDEVS) require it from DomainInterface.DomainBehavior import DomainBehavior diff --git a/Container.py b/Container.py index dc4f2445..d0890e83 100644 --- a/Container.py +++ b/Container.py @@ -61,16 +61,12 @@ from tempfile import gettempdir from traceback import format_exception - from math import * ### for eval -import DomainInterface.MasterModel - if builtins.__dict__.get('GUI_FLAG',True): import ConnectDialog import DiagramConstantsDialog import SpreadSheet - #from PluginManager import PluginManager import ZipManager import DropTarget import PlotGUI @@ -385,6 +381,7 @@ def makeDEVSInstance(diagram = None): if diagram.getDEVSModel(): diagram.ClearAllPorts() else: + import DomainInterface.MasterModel diagram.setDEVSModel(DomainInterface.MasterModel.Master()) ### shape list of diagram diff --git a/DEVSimPy-v4_0_Container.svg b/DEVSimPy-v4_0_Container.svg new file mode 100644 index 00000000..e69de29b diff --git a/DomainInterface/DomainBehavior.py b/DomainInterface/DomainBehavior.py index 53b1e5b9..7c2bf2ee 100644 --- a/DomainInterface/DomainBehavior.py +++ b/DomainInterface/DomainBehavior.py @@ -48,7 +48,7 @@ ### for py 3.X import importlib BaseDEVS = importlib.import_module("DEVSKernel%s.DEVS"%d) - + ### for py 2.X #exec("import DEVSKernel%s.DEVS as BaseDEVS"%(d)) diff --git a/DomainInterface/MasterModel.py b/DomainInterface/MasterModel.py index 4444ddfd..77c25b15 100644 --- a/DomainInterface/MasterModel.py +++ b/DomainInterface/MasterModel.py @@ -46,9 +46,9 @@ ### for py 3.X import importlib BaseDEVS = importlib.import_module("DEVSKernel%s.DEVS"%d) - + #exec("import DEVSKernel%s.DEVS as BaseDEVS"%(d)) - + #import DomainStructure ### ====================================================================== # diff --git a/Editor.py b/Editor.py index 8366d4bd..77b859d4 100644 --- a/Editor.py +++ b/Editor.py @@ -27,12 +27,12 @@ import keyword import inspect import zipfile -import imp import threading import re import codecs import tabnanny import builtins +import types import traceback from traceback import format_exception, extract_tb @@ -99,7 +99,7 @@ def getObjectFromString(scriptlet): else: # Create the new 'temp' module. - temp = imp.new_module("temp") + temp = types.ModuleType('temp') sys.modules["temp"] = temp ### there is syntaxe error ? diff --git a/LibPanel.py b/LibPanel.py index edcc8f65..5f0c602c 100644 --- a/LibPanel.py +++ b/LibPanel.py @@ -117,13 +117,13 @@ def BuildToolbar(self): if wx.VERSION_STRING < '4.0': tb.AddTool(Menu.ID_NEW_LIB, wx.Bitmap(os.path.join(ICON_PATH_16_16,'db+2.png')), shortHelpString=_('Import'), longHelpString=_('Import new libraries from directory')) tb.AddTool(Menu.ID_DELETE_LIB, wx.Bitmap(os.path.join(ICON_PATH_16_16,'db-2.png')), shortHelpString=_('Delete'), longHelpString=_('Delete the selected libraries')) - tb.AddTool(Menu.ID_REFRESH_LIB, wx.Bitmap(os.path.join(ICON_PATH_16_16,'db_refresh2.png')), shortHelpString=_('Refresh'), longHelpString=_('Force the refresh of the loaded libraries')) + tb.AddTool(Menu.ID_REFRESH_LIB, wx.Bitmap(os.path.join(ICON_PATH_16_16,'db_refresh2.png')), shortHelpString=_('Reload'), longHelpString=_('Force to reload libraries')) #tb.AddTool(Menu.ID_IMPORT_LIB, wx.Bitmap(os.path.join(ICON_PATH_16_16,'dbimport2.png')), shortHelpString=_('Import library'), longHelpString=_('Call the import manager')) tb.AddTool(Menu.ID_HELP_LIB, wx.Bitmap(os.path.join(ICON_PATH_16_16, 'dbinfo2.png')), shortHelpString=_('Help'), longHelpString=_('Information about import manager')) else: tb.AddTool(Menu.ID_NEW_LIB, "", wx.Bitmap(os.path.join(ICON_PATH_16_16,'db+2.png')), shortHelp=_('Import')) tb.AddTool(Menu.ID_DELETE_LIB, "", wx.Bitmap(os.path.join(ICON_PATH_16_16,'db-2.png')), shortHelp=_('Delete')) - tb.AddTool(Menu.ID_REFRESH_LIB, "", wx.Bitmap(os.path.join(ICON_PATH_16_16,'db_refresh2.png')), shortHelp=_('Refresh')) + tb.AddTool(Menu.ID_REFRESH_LIB, "", wx.Bitmap(os.path.join(ICON_PATH_16_16,'db_refresh2.png')), shortHelp=_('Reload')) tb.AddTool(Menu.ID_HELP_LIB, "", wx.Bitmap(os.path.join(ICON_PATH_16_16, 'dbinfo2.png')), shortHelp=_('Help')) tb.AddCheckTool(Menu.ID_MCC_LIB, '', wx.Bitmap(os.path.join(ICON_PATH_16_16,'a-z.png')), shortHelp='MacCabe') tb.ToggleTool(Menu.ID_MCC_LIB, True) diff --git a/LibraryTree.py b/LibraryTree.py index 3c2b0913..0bd63af4 100644 --- a/LibraryTree.py +++ b/LibraryTree.py @@ -426,7 +426,7 @@ def GetItemChildren(self, item, recursively = False): def GetPYFileList(dName, ext=".py"): """ Return .py files that are instanciable. """ - + ### import are here because the simulator (PyDEVS or PyPDEVS) require it from DomainInterface.DomainBehavior import DomainBehavior diff --git a/Menu.py b/Menu.py index 4a04484a..ca61bf3c 100644 --- a/Menu.py +++ b/Menu.py @@ -768,7 +768,7 @@ def __init__(self, parent): wx.Menu.__init__(self) new = wx.MenuItem(self, ID_NEW_LIB, _('New/Import'), _('Create or import library')) - refresh = wx.MenuItem(self, ID_REFRESH_LIB, _('Refresh'), _('Refresh library')) + refresh = wx.MenuItem(self, ID_REFRESH_LIB, _('Reload'), _('Reload library')) #upgrade = wx.MenuItem(self, ID_UPGRADE_LIB, _('Upgrade'), _('Upgrade library')) info = wx.MenuItem(self, ID_HELP_LIB, _('Help'), _('Library description')) diff --git a/Mixins/Plugable.py b/Mixins/Plugable.py index 30ce55d1..7dcff9ed 100644 --- a/Mixins/Plugable.py +++ b/Mixins/Plugable.py @@ -23,7 +23,6 @@ import sys import os import zipimport -import imp import inspect import types import zipfile @@ -53,7 +52,7 @@ def Load_Module(fileName): code = importer.get_code(old_plugin_name) # Create the new 'temp' module. - temp = imp.new_module(new_plugin_name) + temp = types.ModuleType(new_plugin_name) sys.modules[new_plugin_name] = temp ### there is syntax error ? diff --git a/NetManager.py b/NetManager.py index bb6d7f2e..d82f4e9d 100644 --- a/NetManager.py +++ b/NetManager.py @@ -12,8 +12,8 @@ """ import sys -import imp import http.client +import types from urllib.parse import urlparse class Net: @@ -40,7 +40,7 @@ def GetMoldule(python_file=""): pass ### make new module - mod = imp.new_module(module_name) + mod = types.ModuleType(module_name) sys.modules[module_name] = mod mod.__file__ = self._py_net_file diff --git a/PluginsGUI.py b/PluginsGUI.py index 1ccdbd1e..7587660f 100644 --- a/PluginsGUI.py +++ b/PluginsGUI.py @@ -310,7 +310,7 @@ def Importing(self, root, basename): ### if module is exception (or tuple) if not inspect.ismodule(module): error = str(module) - module = importlib.new_module(basename) + module = types.ModuleType(basename) module.__doc__ = error module.__file__ = None diff --git a/PreferencesGUI.py b/PreferencesGUI.py index 02ea2b20..0a63929a 100644 --- a/PreferencesGUI.py +++ b/PreferencesGUI.py @@ -469,7 +469,7 @@ def onSc(self, evt): self.sim_defaut_plot_dyn_freq = val def OnApply(self, evt): - """ Apply changes + """ Apply changes. """ ### Reload DomainBehavior and DomainStructure @@ -478,26 +478,18 @@ def OnApply(self, evt): builtins.__dict__['DEFAULT_DEVS_DIRNAME'] = self.default_devs_dir ### recompile the modules. - ### recompile DomainInterface.DomainBehavior with all loaded module depending on this one - d = copy.copy(sys.modules) - for m in d: - if d[m]: - try: - clsmembers = inspect.getmembers(d[m], inspect.isclass) - if clsmembers != [] and clsmembers[0][0] == 'DomainBehavior': - module_path = os.path.dirname(d[m].__file__) - ### if m come from amd or cmd, pass path to recompile method to differentiate - if zipfile.is_zipfile(module_path): - ReloadModule.recompile(module_path) - else: - ReloadModule.recompile(m) - except Exception as info: - sys.stdout.write("Exception in PreferenceGui") - sys.stdout.write(str(info)) - + ### recompile DomainInterface.DomainBehavior , DomainInterfaceStructure and MasterModel + ### recompile all librairies that depend on DomainBehavior (all loaded lib) + + ReloadModule.recompile("DomainInterface.DomainBehavior") ReloadModule.recompile("DomainInterface.DomainStructure") ReloadModule.recompile("DomainInterface.MasterModel") + mainW = wx.GetApp().GetTopWindow() + nb1 = mainW.GetControlNotebook() + tree = nb1.GetTree() + tree.UpdateAll() + ### enable the priority (DEVS select function) icon depending on the selected DEVS kernel mainW = wx.GetApp().GetTopWindow() tb = mainW.GetToolBar() diff --git a/RQ.py b/RQ.py deleted file mode 100644 index ef873b28..00000000 --- a/RQ.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -#------------------------------------------------------------------------------- -# Name: -# -# Model: -# Author: -# -# Created: <2010-03-24> -#------------------------------------------------------------------------------- - -from .DomainInterface.DomainBehavior import DomainBehavior -from Object import Message - -### Model class ---------------------------------------------------------------- -class RQ(DomainBehavior): - - def __init__(self): - DomainBehavior.__init__(self) - self.state = {'status': 'INACTIF', 'sigma': INFINITY} - self.phase = 'Free' - self.jobsList = [] - - def intTransition(self): - self.state['sigma'] = INFINITY - self.state['status'] = 'IDLE' - - def extTransition(self): - np=0 - self.msg= self.peek(self.IPorts[np]) - while(self.msg == None): - np+=1 - self.msg= self.peek(self.IPorts[np]) - - if np == 0 : - # we add to the job list a new job that is formed of the arrival time and the time that it needs to be executed in the CPU - self.jobsList.insert(0,[self.msg.value,self.msg.time]) - if self.phase == 'Free': - self.state['status'] = 'ACTIF' - self.state['sigma'] = 0.01 - else: - self.phase = 'Free' - self.state['status'] = 'ACTIF' - self.state['sigma'] = 0.01 - - def outputFnc(self): - # we verify that we have a job and CPU is free then we send a message that contains the execution time and the sent time - if (len(self.jobsList) > 0 and self.phase == 'Free'): - job = self.jobsList.pop() - job[1] = self.timeNext - self.poke(self.OPorts[0],Message(job[0],job[1])) - self.phase = 'Busy' - - def timeAdvance(self): - return self.state['sigma'] diff --git a/ReloadModule.py b/ReloadModule.py index 9ab7377d..fae985fe 100644 --- a/ReloadModule.py +++ b/ReloadModule.py @@ -8,14 +8,18 @@ import types import pkgutil +import gettext +_ = gettext.gettext + from traceback import format_exception from Utilities import listf def reloadall(module): importlib.reload(module) - for child in pkgutil.walk_packages(module.__path__): - if isinstance(child, types.ModuleType): - reloadall(child) + if hasattr(module, '__path__'): + for child in pkgutil.walk_packages(module.__path__): + if isinstance(child, types.ModuleType): + reloadall(child) def recompile(modulename): """ recompile module from modulename @@ -29,10 +33,7 @@ def recompile(modulename): else: try: ### first, see if the module can be imported at all... - name, ext = os.path.splitext(modulename) - pkg = '.'.join(modulename.split('.')[0:-1]) - tmp = importlib.import_module(name, package=pkg) - #tmp = __import__(modulename, globals(), locals(), fromlist = [modulename.split('.')[-1]]) + tmp = __import__(modulename, globals(), locals(), fromlist = [modulename.split('.')[-1]]) except Exception as info: return info @@ -65,8 +66,52 @@ def recompile(modulename): ### reload recursivelly! try: reloadall(tmp) - return sys.modules[tmp.__name__] - except: - sys.stdout.write('Error trying to reload dependencies in recompile module!') - else: - return importlib.reload(tmp) \ No newline at end of file + except Exception as info: + sys.stdout.write(_('Error trying to reload dependencies in recompile module: %s\n')%info) + finally: + return importlib.reload(sys.modules[modulename]) + + #return importlib.reload(tmp) + +def recompile2(modulename): + """ recompile module from modulename + """ + + ### modulename is file type + if os.path.isfile(modulename) and os.path.exists(modulename): + import ZipManager + zf = ZipManager.Zip(modulename) + return zf.Recompile() + else: + + try: + #name, ext = os.path.splitext(modulename) + #pkg = '.'.join(modulename.split('.')[0:-1]) + #tmp = importlib.import_module(name, package=pkg) + + ### first, see if the module can be imported at all... + tmp = __import__(modulename, globals(), locals(), fromlist = [modulename.split('.')[-1]]) + + except Exception as info: + return info + + ### Use the imported module to determine its actual path + pycfile = os.path.abspath(tmp.__file__) + modulepath = pycfile.replace(".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. + compile(code, modulename, "exec") + + + ### Ok, it compiled. But will it execute without error? + exec(compile(open(modulepath).read(), modulepath, 'exec'), globals()) + + reloadall(tmp) + + ### at this point, the code both compiled and ran without error. Load it up + ### replacing the original code. + return importlib.reload(sys.modules[modulename]) \ No newline at end of file diff --git a/Utilities.py b/Utilities.py index 21e38efe..6f33c8cc 100644 --- a/Utilities.py +++ b/Utilities.py @@ -32,8 +32,7 @@ import inspect import shutil import configparser -import linecache -import imp +import linecache import tempfile import pathlib @@ -449,7 +448,7 @@ def getObjectFromString(scriptlet): return info else: # Create the new 'temp' module. - temp = imp.new_module("temp") + temp = types.ModuleType("temp") sys.modules["temp"] = temp ### there is syntaxe error ? diff --git a/WizardGUI.py b/WizardGUI.py index 8a0ec953..ac4eb403 100644 --- a/WizardGUI.py +++ b/WizardGUI.py @@ -406,6 +406,7 @@ def python_path_call_back(evt): fn = evt.GetEventObject().GetValue() cls = Components.GetClass(fn) if inspect.isclass(cls): + ### import are here because the simulator (PyDEVS or PyPDEVS) require it from DomainInterface.DomainBehavior import DomainBehavior from DomainInterface.DomainStructure import DomainStructure diff --git a/ZipManager.py b/ZipManager.py index 897d2e2c..4b18d1b1 100644 --- a/ZipManager.py +++ b/ZipManager.py @@ -64,6 +64,7 @@ def getPythonModelFileName(fn:str)->str: return python_file ### else test if the python file containing the class inherit of the DomainBehavior or DomainStructure else: + import Components cls = Components.GetClass(os.path.join(fn, python_file)) @@ -338,32 +339,33 @@ def ReImport(self): Zip.ClearCache(self.fn) # import module - try: +# try: + + ### reload submodule from module dependencies! + module = sys.modules[self.fullname] + domain_name = os.path.basename(os.path.dirname(self.fn)) + for name in dir(module): + if type(getattr(module, name)) == types.ModuleType: + ### TODO: only reload the local package (not 'sys' and so one) + importlib.reload(get_from_modules(name)) + + ### clear to clean the import after exporting model (amd or cmd) and reload within the same instance of DEVSimPy + zipimport._zip_directory_cache.clear() - ### realod submodule from module dependencies! - module = sys.modules[self.fullname] - domain_name = os.path.basename(os.path.dirname(self.fn)) - for name in dir(module): - if type(getattr(module, name)) == types.ModuleType: - ### TODO: only reload the local package (not 'sys' and so one) - importlib.reload(get_from_modules(name)) - - ### clear to clean the import after exporting model (amd or cmd) and reload within the same instance of DEVSimPy - zipimport._zip_directory_cache.clear() + ### reload module + module = self.ImportModule() + return module - ### reload module - module = self.ImportModule() - - except Exception as info: - msg_i = _("Error in execution: ") - msg_o = listf(format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])) - try: - sys.stderr.write( msg_i + str(sys.exc_info()[0]) +"\r\n" + msg_o) - except UnicodeDecodeError: - sys.stderr.write( msg_i + str(sys.exc_info()[0]).decode('latin-1').encode("utf-8") +"\r\n" + msg_o) - return info - else: - return module +# except Exception as info: +# msg_i = _("Error in execution: ") +# msg_o = listf(format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])) +# try: +# sys.stderr.write( msg_i + str(sys.exc_info()[0]) +"\r\n" + msg_o) +# except UnicodeDecodeError: +# sys.stderr.write( msg_i + str(sys.exc_info()[0]).decode('latin-1').encode("utf-8") +"\r\n" + msg_o) +# return info +# else: +# return module @staticmethod def ClearCache(fn:str)->None: