def __killMyPort(port, filedict):
    # bug fix: ensure port is an integer
    if port:
        port = int(port)

    try:
        with open(filedict, 'r') as fpid:
            process_ids=pickle.load(fpid)
            for process_id in process_ids:
                for pid, cmd in process_id.items():
                    if verbose(): print "stop process %s : %s"% (pid, cmd[0])
                    try:
                        from salome_utils import killpid
                        killpid(int(pid))
                    except:
                        if verbose(): print "  ------------------ process %s : %s not found"% (pid, cmd[0])
                        pass
                    pass # for pid ...
                pass # for process_id ...
            # end with
    except:
        print "Cannot find or open SALOME PIDs file for port", port
        pass
    os.remove(filedict)
    pass
Exemplo n.º 2
0
def __killMyPort(port, filedict):
    # bug fix: ensure port is an integer
    if port:
        port = int(port)

    try:
        with open(filedict, 'r') as fpid:
            process_ids = pickle.load(fpid)
            for process_id in process_ids:
                for pid, cmd in process_id.items():
                    if verbose(): print "stop process %s : %s" % (pid, cmd[0])
                    try:
                        from salome_utils import killpid
                        killpid(int(pid))
                    except:
                        if verbose():
                            print "  ------------------ process %s : %s not found" % (
                                pid, cmd[0])
                        pass
                    pass  # for pid ...
                pass  # for process_id ...
            # end with
    except:
        print "Cannot find or open SALOME PIDs file for port", port
        pass
    os.remove(filedict)
    pass
Exemplo n.º 3
0
def killMyPort(port):
    """
    Kill SALOME session running on the specified port.
    Parameters:
    - port - port number
    """
    # bug fix: ensure port is an integer
    if port:
        port = int(port)

    try:
        import PortManager  # do not remove! Test for PortManager availability!
        filedict = getPiDict(port)
        if not os.path.isfile(filedict):  # removed by previous call, see (1)
            if verbose():
                print "SALOME on port %s: already removed by previous call" % port
            # Remove port from PortManager config file
            try:
                from PortManager import releasePort
                if verbose():
                    print "Removing port from PortManager configuration file"
                releasePort(port)
            except ImportError:
                pass
            return
    except:
        pass

    # try to shutdown session normally
    import threading, time
    threading.Thread(target=shutdownMyPort, args=(port, True)).start()
    time.sleep(
        3
    )  # wait a little, then kill processes (should be done if shutdown procedure hangs up)

    try:
        import PortManager  # do not remove! Test for PortManager availability!
        filedict = getPiDict(port)
        #filedict = __guessPiDictFilename(port)
        import glob
        all_files = glob.glob("%s*" % filedict)
        for f in all_files:
            __killMyPort(port, f)
    except ImportError:
        filedict = __guessPiDictFilename(port)
        __killMyPort(port, filedict)
    #

    appliCleanOmniOrbConfig(port)
    pass
def killMyPort(port):
    """
    Kill SALOME session running on the specified port.
    Parameters:
    - port - port number
    """
    # bug fix: ensure port is an integer
    if port:
        port = int(port)

    try:
        import PortManager # do not remove! Test for PortManager availability!
        filedict = getPiDict(port)
        if not os.path.isfile(filedict): # removed by previous call, see (1)
            if verbose():
                print "SALOME on port %s: already removed by previous call"%port
            # Remove port from PortManager config file
            try:
                from PortManager import releasePort
                if verbose():
                    print "Removing port from PortManager configuration file"
                releasePort(port)
            except ImportError:
                pass
            return
    except:
        pass

    # try to shutdown session normally
    import threading, time
    threading.Thread(target=shutdownMyPort, args=(port,True)).start()
    time.sleep(3) # wait a little, then kill processes (should be done if shutdown procedure hangs up)

    try:
        import PortManager # do not remove! Test for PortManager availability!
        filedict = getPiDict(port)
        #filedict = __guessPiDictFilename(port)
        import glob
        all_files = glob.glob("%s*"%filedict)
        for f in all_files:
            __killMyPort(port, f)
    except ImportError:
        filedict = __guessPiDictFilename(port)
        __killMyPort(port, filedict)
    #

    appliCleanOmniOrbConfig(port)
    pass
Exemplo n.º 5
0
def __guessPiDictFilename(port):
    from salome_utils import getShortHostName, getHostName
    filedicts = [
        # new-style dot-prefixed pidict file
        getPiDict(port, hidden=True),
        # provide compatibility with old-style pidict file (not dot-prefixed)
        getPiDict(port, hidden=False),
        # provide compatibility with old-style pidict file (short hostname)
        getPiDict(port, hidden=True, hostname=getShortHostName()),
        # provide compatibility with old-style pidict file (not dot-prefixed, short hostname
        getPiDict(port, hidden=False, hostname=getShortHostName()),
        # provide compatibility with old-style pidict file (long hostname)
        getPiDict(port, hidden=True, hostname=getHostName()),
        # provide compatibility with old-style pidict file (not dot-prefixed, long hostname)
        getPiDict(port, hidden=False, hostname=getHostName())
    ]

    log_msg = ""
    for filedict in filedicts:
        log_msg += "Trying %s..." % filedict
        if os.path.exists(filedict):
            log_msg += "   ... OK\n"
            break
        else:
            log_msg += "   ... not found\n"

    if verbose():
        print log_msg

    return filedict
Exemplo n.º 6
0
    def update(self, name=None, iteration=None, order=None, source=None):
        """
    This function can be used to update the meta-data associated
    to this field. It can modify the name, the iteration, the
    order and the source.
    """
        if name is None:
            name = self.fieldname
        if iteration is None:
            iteration = self.iteration
        if order is None:
            order = self.order
        if source is None:
            source = self.source

        dataManager.updateFieldMetadata(self.id, name, iteration, order,
                                        source)
        self.__fieldHandler.fieldname = name
        self.__fieldHandler.iteration = iteration
        self.__fieldHandler.order = order
        self.__fieldHandler.source = source
        # WARN: Note that you have to update directly the fieldHandler
        # object because of the presence of the method __setattr__
        # that make the proxy to this update method

        # Finally, we have to notify the GUI for update of field prestations
        #self.__notifyGui_update()
        from medcalc.medevents import notifyGui_updateField
        notifyGui_updateField(self.id)

        # Print for visual control
        from salome_utils import verbose
        if verbose():
            print(self.__repr__())
def __guessPiDictFilename(port):
    from salome_utils import getShortHostName, getHostName
    filedicts = [
        # new-style dot-prefixed pidict file
        getPiDict(port, hidden=True),
        # provide compatibility with old-style pidict file (not dot-prefixed)
        getPiDict(port, hidden=False),
        # provide compatibility with old-style pidict file (short hostname)
        getPiDict(port, hidden=True, hostname=getShortHostName()),
        # provide compatibility with old-style pidict file (not dot-prefixed, short hostname
        getPiDict(port, hidden=False, hostname=getShortHostName()),
        # provide compatibility with old-style pidict file (long hostname)
        getPiDict(port, hidden=True, hostname=getHostName()),
        # provide compatibility with old-style pidict file (not dot-prefixed, long hostname)
        getPiDict(port, hidden=False, hostname=getHostName())
        ]

    log_msg = ""
    for filedict in filedicts:
        log_msg += "Trying %s..."%filedict
        if os.path.exists(filedict):
            log_msg += "   ... OK\n"
            break
        else:
            log_msg += "   ... not found\n"

    if verbose():
        print log_msg

    return filedict
Exemplo n.º 8
0
 def __init__(self, fieldHandler):
     """
 This defines the wrapping on the field specified by its
 fieldHandler id.
 """
     self.__fieldHandler = fieldHandler
     self.__restriction = None
     from salome_utils import verbose
     if verbose():
         print(self.__repr__())
Exemplo n.º 9
0
def extend_path(pname):
    for dir in sys.path:
        if not isinstance(dir, basestring) or not os.path.isdir(dir) or not dir.endswith(MATCH_ENDING_PATTERN):
            continue
        subdir = os.path.join(dir, pname)
        # XXX This may still add duplicate entries to path on
        # case-insensitive filesystems
        if os.path.isdir(subdir) and subdir not in __path__:
            if verbose(): print "INFO - The directory %s is appended to sys.path" % subdir
            __path__.append(subdir)
Exemplo n.º 10
0
def extend_path(pname):
    for dir in sys.path:
        if not isinstance(dir, basestring) or not os.path.isdir(
                dir) or not dir.endswith(MATCH_ENDING_PATTERN):
            continue
        subdir = os.path.join(dir, pname)
        # XXX This may still add duplicate entries to path on
        # case-insensitive filesystems
        if os.path.isdir(subdir) and subdir not in __path__:
            if verbose():
                print "INFO - The directory %s is appended to sys.path" % subdir
            __path__.append(subdir)
Exemplo n.º 11
0
    def importFile(self, fname):
        # get absolute name
        if os.path.isabs(fname):
            absfname = fname
        else:
            absfname = os.path.join(os.path.dirname(self.fileName), fname)

        # check existing and registry file
        for ext in ["", ".xml", ".XML"]:
            if os.path.exists(absfname + ext):
                absfname += ext
                if absfname in self.importHistory:
                    if verbose():
                        print "Configure parser: Warning : file %s is already imported" % absfname
                    return  # already imported
                break
            pass
        else:
            if verbose():
                print "Configure parser: Error : file %s does not exist" % absfname
            return

        # importing file
        try:
            # copy current options
            import copy
            opts = copy.deepcopy(self.opts)
            # import file
            imp = xml_parser(absfname, opts, self.importHistory)
            # merge results
            for key in imp.opts.keys():
                if not self.opts.has_key(key):
                    self.opts[key] = imp.opts[key]
                    pass
                pass
            pass
        except:
            if verbose():
                print "Configure parser: Error : can not read configuration file %s" % absfname
        pass
    def importFile(self, fname):
        # get absolute name
        if os.path.isabs (fname) :
            absfname = fname
        else:
            absfname = os.path.join(os.path.dirname(self.fileName), fname)

        # check existing and registry file
        for ext in ["", ".xml", ".XML"] :
            if os.path.exists(absfname + ext) :
                absfname += ext
                if absfname in self.importHistory :
                    if verbose(): print "Configure parser: Warning : file %s is already imported" % absfname
                    return # already imported
                break
            pass
        else:
            if verbose(): print "Configure parser: Error : file %s does not exist" % absfname
            return

        # importing file
        try:
            # copy current options
            import copy
            opts = copy.deepcopy(self.opts)
            # import file
            imp = xml_parser(absfname, opts, self.importHistory)
            # merge results
            for key in imp.opts.keys():
                if not self.opts.has_key(key):
                    self.opts[key] = imp.opts[key]
                    pass
                pass
            pass
        except:
            if verbose(): print "Configure parser: Error : can not read configuration file %s" % absfname
        pass
 def __init__(self, fileName, _opts, _importHistory):
     #warning _importHistory=[] is NOT good: is NOT empty,reinitialized after first call
     if verbose(): print "Configure parser: processing %s ..." % fileName
     self.fileName = os.path.abspath(fileName)
     self.importHistory = _importHistory
     self.importHistory.append(self.fileName)
     self.space = []
     self.opts = _opts
     self.section = section_to_skip
     parser = xml.sax.make_parser()
     parser.setContentHandler(self)
     parser.parse(fileName)
     standalone, embedded = process_containers_params( self.opts.get( standalone_nam ),
                                                       self.opts.get( embedded_nam ) )
     if standalone is not None:
         self.opts[ standalone_nam ] = standalone
     if embedded is not None:
         self.opts[ embedded_nam ] = embedded
     pass
Exemplo n.º 14
0
 def __init__(self, fileName, _opts, _importHistory):
     #warning _importHistory=[] is NOT good: is NOT empty,reinitialized after first call
     if verbose(): print "Configure parser: processing %s ..." % fileName
     self.fileName = os.path.abspath(fileName)
     self.importHistory = _importHistory
     self.importHistory.append(self.fileName)
     self.space = []
     self.opts = _opts
     self.section = section_to_skip
     parser = xml.sax.make_parser()
     parser.setContentHandler(self)
     parser.parse(fileName)
     standalone, embedded = process_containers_params(
         self.opts.get(standalone_nam), self.opts.get(embedded_nam))
     if standalone is not None:
         self.opts[standalone_nam] = standalone
     if embedded is not None:
         self.opts[embedded_nam] = embedded
     pass
Exemplo n.º 15
0
    smesh = None
    pass

# load plugins and add dynamically generated methods to Mesh class,
# the same for for global variables declared by plug-ins
from salome.smesh.smeshBuilder import *
from salome.smesh.smeshBuilder import Mesh, algoCreator
for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
    #
    #print "pluginName: ", pluginName
    pluginBuilderName = pluginName + "Builder"
    try:
        exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
    except Exception, e:
        from salome_utils import verbose
        if verbose(): print "Exception while loading %s: %s" % ( pluginBuilderName, e )
        continue
    exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
    plugin = eval( pluginBuilderName )

    # add methods creating algorithms to Mesh
    for k in dir( plugin ):
        if k[0] == '_': continue
        algo = getattr( plugin, k )
        if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
            if not hasattr( Mesh, algo.meshMethod ):
                setattr( Mesh, algo.meshMethod, algoCreator() )
                pass
            getattr( Mesh, algo.meshMethod ).add( algo )
            pass
        pass
Exemplo n.º 16
0
def appliCleanOmniOrbConfig(port):
    """
    Remove omniorb config files related to the port in SALOME application:
    - ${OMNIORB_USER_PATH}/.omniORB_${USER}_${HOSTNAME}_${NSPORT}.cfg
    - ${OMNIORB_USER_PATH}/.omniORB_${USER}_last.cfg
    the last is removed only if the link points to the first file.
    """
    if verbose():
        print "clean OmniOrb config for port %s" % port

    from salome_utils import generateFileName, getUserName
    omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
    if omniorbUserPath is None:
        #Run outside application context
        pass
    else:
        omniorb_config = generateFileName(omniorbUserPath,
                                          prefix="omniORB",
                                          extension="cfg",
                                          hidden=True,
                                          with_username=True,
                                          with_hostname=True,
                                          with_port=port)
        last_running_config = generateFileName(omniorbUserPath,
                                               prefix="omniORB",
                                               with_username=True,
                                               suffix="last",
                                               extension="cfg",
                                               hidden=True)
        if os.access(last_running_config, os.F_OK):
            if not sys.platform == 'win32':
                pointedPath = os.readlink(last_running_config)
                if pointedPath[0] != '/':
                    pointedPath = os.path.join(
                        os.path.dirname(last_running_config), pointedPath)
                    pass
                if pointedPath == omniorb_config:
                    os.unlink(last_running_config)
                    pass
                pass
            else:
                os.remove(last_running_config)
                pass
            pass

        if os.access(omniorb_config, os.F_OK):
            os.remove(omniorb_config)
            pass

        if os.path.lexists(last_running_config): return

        #try to relink last.cfg to an existing config file if any
        files = glob.glob(
            os.path.join(omniorbUserPath,
                         ".omniORB_" + getUserName() + "_*.cfg"))
        current_config = None
        current = 0
        for f in files:
            stat = os.stat(f)
            if stat.st_atime > current:
                current = stat.st_atime
                current_config = f
        if current_config:
            if sys.platform == "win32":
                import shutil
                shutil.copyfile(os.path.normpath(current_config),
                                last_running_config)
                pass
            else:
                os.symlink(os.path.normpath(current_config),
                           last_running_config)
                pass
            pass
        pass
    pass
def appliCleanOmniOrbConfig(port):
    """
    Remove omniorb config files related to the port in SALOME application:
    - ${OMNIORB_USER_PATH}/.omniORB_${USER}_${HOSTNAME}_${NSPORT}.cfg
    - ${OMNIORB_USER_PATH}/.omniORB_${USER}_last.cfg
    the last is removed only if the link points to the first file.
    """
    if verbose():
        print "clean OmniOrb config for port %s"%port

    from salome_utils import generateFileName, getUserName
    omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
    if omniorbUserPath is None:
        #Run outside application context
        pass
    else:
        omniorb_config      = generateFileName(omniorbUserPath, prefix="omniORB",
                                               extension="cfg",
                                               hidden=True,
                                               with_username=True,
                                               with_hostname=True,
                                               with_port=port)
        last_running_config = generateFileName(omniorbUserPath, prefix="omniORB",
                                               with_username=True,
                                               suffix="last",
                                               extension="cfg",
                                               hidden=True)
        if os.access(last_running_config,os.F_OK):
            if not sys.platform == 'win32':
                pointedPath = os.readlink(last_running_config)
                if pointedPath[0] != '/':
                    pointedPath=os.path.join(os.path.dirname(last_running_config), pointedPath)
                    pass
                if pointedPath == omniorb_config:
                    os.unlink(last_running_config)
                    pass
                pass
            else:
                os.remove(last_running_config)
                pass
            pass

        if os.access(omniorb_config,os.F_OK):
            os.remove(omniorb_config)
            pass

        if os.path.lexists(last_running_config):return

        #try to relink last.cfg to an existing config file if any
        files = glob.glob(os.path.join(omniorbUserPath,".omniORB_"+getUserName()+"_*.cfg"))
        current_config=None
        current=0
        for f in files:
          stat=os.stat(f)
          if stat.st_atime > current:
            current=stat.st_atime
            current_config=f
        if current_config:
          if sys.platform == "win32":
            import shutil
            shutil.copyfile(os.path.normpath(current_config), last_running_config)
            pass
          else:
            os.symlink(os.path.normpath(current_config), last_running_config)
            pass
          pass
        pass
    pass
def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgname, exeName=None):
    ###
    # Collect launch configuration files:
    # - The environment variable "<appname>Config" (SalomeAppConfig) which can
    #   define a list of directories (separated by ':' or ';' symbol) is checked
    # - If the environment variable "<appname>Config" is not set, only
    #   ${GUI_ROOT_DIR}/share/salome/resources/gui is inspected
    # - ${GUI_ROOT_DIR}/share/salome/resources/gui directory is always inspected
    #   so it is not necessary to put it in the "<appname>Config" variable
    # - The directories which are inspected are checked for files "<appname?salomeappname>.xml"
    #  (SalomeApp.xml) which define SALOME configuration
    # - These directories are analyzed beginning from the last one in the list,
    #   so the first directory listed in "<appname>Config" environment variable
    #   has higher priority: it means that if some configuration options
    #   is found in the next analyzed cofiguration file - it will be replaced
    # - The last configuration file which is parsed is user configuration file
    #   situated in the home directory (if it exists):
    #   * ~/.config/salome/.<appname>rc[.<version>]" for Linux (e.g. ~/.config/salome/.SalomeApprc.6.4.0)
    #   * ~/<appname>.xml[.<version>] for Windows (e.g. ~/SalomeApp.xml.6.4.0)
    # - Command line options have the highest priority and replace options
    #   specified in configuration file(s)
    ###

    if theAdditionalOptions is None:
        theAdditionalOptions = []

    global args
    config_var = appname+'Config'

    # check KERNEL_ROOT_DIR
    kernel_root_dir = os.environ.get("KERNEL_ROOT_DIR", None)
    if kernel_root_dir is None:
        print """
        For each SALOME module, the environment variable <moduleN>_ROOT_DIR must be set.
        KERNEL_ROOT_DIR is mandatory.
        """
        sys.exit(1)

    ############################
    # parse command line options
    pars = CreateOptionParser(theAdditionalOptions, exeName=exeName)
    (cmd_opts, cmd_args) = pars.parse_args(sys.argv[1:])
    ############################

    # Process --print-port option
    if cmd_opts.print_port:
        from searchFreePort import searchFreePort
        searchFreePort({})
        print "port:%s"%(os.environ['NSPORT'])

        try:
            import PortManager
            PortManager.releasePort(os.environ['NSPORT'])
        except ImportError:
            pass

        sys.exit(0)
        pass

    # set resources variable SalomeAppConfig if it is not set yet
    dirs = []
    if os.getenv(config_var):
        if sys.platform == 'win32':
            dirs += re.split(os.pathsep, os.getenv(config_var))
        else:
            dirs += re.split('[;|:]', os.getenv(config_var))

    gui_available = False
    if os.getenv("GUI_ROOT_DIR"):
        gui_resources_dir = os.path.join(os.getenv("GUI_ROOT_DIR"),'share','salome','resources','gui')
        if os.path.isdir( gui_resources_dir ):
            gui_available = True
            dirs.append(gui_resources_dir)
        pass
    if not gui_available:
        kernel_resources_dir = os.path.join(os.getenv("KERNEL_ROOT_DIR"),'bin','salome','appliskel')
        if os.getenv("KERNEL_ROOT_DIR") and os.path.isdir( kernel_resources_dir ):
          dirs.append(kernel_resources_dir)
        pass
    os.environ[config_var] = os.pathsep.join(dirs)

    dirs.reverse() # reverse order, like in "path" variable - FILO-style processing

    try:
        dirs.remove('') # to remove empty dirs if the variable terminate by ":" or if there are "::" inside
    except:
        pass

    _opts = {} # associative array of options to be filled

    # parse SalomeApp.xml files in directories specified by SalomeAppConfig env variable
    for dir in dirs:
        filename = os.path.join(dir, appname+'.xml')
        if not os.path.exists(filename):
            if verbose(): print "Configure parser: Warning : can not find configuration file %s" % filename
        else:
            try:
                p = xml_parser(filename, _opts, [])
                _opts = p.opts
            except:
                if verbose(): print "Configure parser: Error : can not read configuration file %s" % filename
            pass

    # parse user configuration file
    # It can be set via --resources=<file> command line option
    # or is given from default location (see defaultUserFile() function)
    # If user file for the current version is not found the nearest to it is used
    user_config = cmd_opts.resources
    if not user_config:
        user_config = userFile(appname, cfgname)
        if verbose(): print "Configure parser: user configuration file is", user_config
    if not user_config or not os.path.exists(user_config):
        if verbose(): print "Configure parser: Warning : can not find user configuration file"
    else:
        try:
            p = xml_parser(user_config, _opts, [])
            _opts = p.opts
        except:
            if verbose(): print 'Configure parser: Error : can not read user configuration file'
            user_config = ""

    args = _opts

    args['user_config'] = user_config
    #print "User Configuration file: ", args['user_config']

    # set default values for options which are NOT set in config files
    for aKey in listKeys:
        if not args.has_key( aKey ):
            args[aKey] = []

    for aKey in boolKeys:
        if not args.has_key( aKey ):
            args[aKey] = 0

    if args[file_nam]:
        afile=args[file_nam]
        args[file_nam] = [afile]

    args[appname_nam] = appname

    # get the port number
    my_port = getPortNumber()

    args[port_nam] = my_port

    ####################################################
    # apply command-line options to the arguments
    # each option given in command line overrides the option from xml config file
    #
    # Options: gui, desktop, log_file, resources,
    #          xterm, modules, embedded, standalone,
    #          portkill, killall, interp, splash,
    #          catch_exceptions, pinter

    # GUI/Terminal, Desktop, Splash, STUDY_HDF
    args["session_gui"] = False
    args[batch_nam] = False
    args["study_hdf"] = None
    if cmd_opts.gui is not None:
        args[gui_nam] = cmd_opts.gui
    if cmd_opts.batch is not None:
        args[batch_nam] = True

    if not gui_available:
        args[gui_nam] = False

    if args[gui_nam]:
        args["session_gui"] = True
        if cmd_opts.desktop is not None:
            args["session_gui"] = cmd_opts.desktop
            args[splash_nam]    = cmd_opts.desktop
        if args["session_gui"]:
            if cmd_opts.splash is not None:
                args[splash_nam] = cmd_opts.splash
    else:
        args["session_gui"] = False
        args[splash_nam] = False

    # Logger/Log file
    if cmd_opts.log_file is not None:
        if cmd_opts.log_file == 'CORBA':
            args[logger_nam] = True
        else:
            args[file_nam] = [cmd_opts.log_file]

    # Naming Service port log file
    if cmd_opts.ns_port_log_file is not None:
      args["ns_port_log_file"] = cmd_opts.ns_port_log_file

    # Study files
    for arg in cmd_args:
        if arg[-4:] == ".hdf" and not args["study_hdf"]:
            args["study_hdf"] = arg

    # Python scripts
    from salomeContextUtils import getScriptsAndArgs, ScriptAndArgs
    args[script_nam] = getScriptsAndArgs(cmd_args)
    if args[gui_nam] and args["session_gui"]:
        new_args = []
        for sa_obj in args[script_nam]: # args[script_nam] is a list of ScriptAndArgs objects
            script = re.sub(r'^python.*\s+', r'', sa_obj.script)
            new_args.append(ScriptAndArgs(script=script, args=sa_obj.args, out=sa_obj.out))
        #
        args[script_nam] = new_args

    # xterm
    if cmd_opts.xterm is not None: args[xterm_nam] = cmd_opts.xterm

    # Modules
    if cmd_opts.modules is not None:
        args[modules_nam] = []
        listlist = cmd_opts.modules
        for listi in listlist:
            args[modules_nam] += re.split( "[:;,]", listi)
    else:
        # if --modules (-m) command line option is not given
        # try SALOME_MODULES environment variable
        if os.getenv( "SALOME_MODULES" ):
            args[modules_nam] = re.split( "[:;,]", os.getenv( "SALOME_MODULES" ) )
            pass

    # Embedded
    if cmd_opts.embedded is not None:
        args[embedded_nam] = filter( lambda a: a.strip(), re.split( "[:;,]", cmd_opts.embedded ) )

    # Standalone
    if cmd_opts.standalone is not None:
        args[standalone_nam] = filter( lambda a: a.strip(), re.split( "[:;,]", cmd_opts.standalone ) )

    # Normalize the '--standalone' and '--embedded' parameters
    standalone, embedded = process_containers_params( args.get( standalone_nam ),
                                                      args.get( embedded_nam ) )
    if standalone is not None:
        args[ standalone_nam ] = standalone
    if embedded is not None:
        args[ embedded_nam ] = embedded

    # Kill
    if cmd_opts.portkill is not None: args[portkill_nam] = cmd_opts.portkill
    if cmd_opts.killall  is not None: args[killall_nam]  = cmd_opts.killall

    # Interpreter
    if cmd_opts.interp is not None:
        args[interp_nam] = cmd_opts.interp

    # Exceptions
    if cmd_opts.catch_exceptions is not None:
        args[except_nam] = not cmd_opts.catch_exceptions

    # Relink config file
    if cmd_opts.save_config is not None:
        args['save_config'] = cmd_opts.save_config

    # Interactive python console
    if cmd_opts.pinter is not None:
        args[pinter_nam] = cmd_opts.pinter

    # Gdb session in xterm
    if cmd_opts.gdb_session is not None:
        args[gdb_session_nam] = cmd_opts.gdb_session

    # Ddd session in xterm
    if cmd_opts.ddd_session is not None:
        args[ddd_session_nam] = cmd_opts.ddd_session

    # valgrind session
    if cmd_opts.valgrind_session is not None:
        args[valgrind_session_nam] = cmd_opts.valgrind_session

    # Shutdown servers
    if cmd_opts.shutdown_servers is None:
        args[shutdown_servers_nam] = 0
    else:
        args[shutdown_servers_nam] = cmd_opts.shutdown_servers
        pass

    # Foreground
    if cmd_opts.foreground is None:
        args[foreground_nam] = 1
    else:
        args[foreground_nam] = cmd_opts.foreground
        pass

    # wake up session
    if cmd_opts.wake_up_session is not None:
        args[wake_up_session_nam] = cmd_opts.wake_up_session

    ####################################################
    # Add <theAdditionalOptions> values to args
    for add_opt in theAdditionalOptions:
        cmd = "args[\"{0}\"] = cmd_opts.{0}".format(add_opt.dest)
        exec(cmd)
    ####################################################

    # disable signals handling
    if args[except_nam] == 1:
        os.environ["NOT_INTERCEPT_SIGNALS"] = "1"
        pass

    # now modify SalomeAppConfig environment variable
    # to take into account the SALOME modules
    if os.sys.platform == 'win32':
        dirs = re.split('[;]', os.environ[config_var] )
    else:
        dirs = re.split('[;|:]', os.environ[config_var] )
    for module in args[modules_nam]:
        if module not in ["KERNEL", "GUI", ""] and os.getenv("{0}_ROOT_DIR".format(module)):
            d1 = os.path.join(os.getenv("{0}_ROOT_DIR".format(module)),"share","salome","resources",module.lower())
            d2 = os.path.join(os.getenv("{0}_ROOT_DIR".format(module)),"share","salome","resources")
            #if os.path.exists( "%s/%s.xml"%(d1, appname) ):
            if os.path.exists( os.path.join(d1,"{0}.xml".format(salomeappname)) ):
                dirs.append( d1 )
            #elif os.path.exists( "%s/%s.xml"%(d2, appname) ):
            elif os.path.exists( os.path.join(d2,"{0}.xml".format(salomeappname)) ):
                dirs.append( d2 )
        else:
            #print "* '"+m+"' should be deleted from ",args[modules_nam]
            pass

    # Test
    if cmd_opts.test_script_file is not None:
        args[test_nam] = []
        filename = cmd_opts.test_script_file
        args[test_nam] += re.split( "[:;,]", filename )

    # Play
    if cmd_opts.play_script_file is not None:
        args[play_nam] = []
        filename = cmd_opts.play_script_file
        args[play_nam] += re.split( "[:;,]", filename )

    # Server launch command
    if cmd_opts.server_launch_mode is not None:
        args["server_launch_mode"] = cmd_opts.server_launch_mode

    # Server launch command
    if cmd_opts.use_port is not None:
        min_port = 2810
        max_port = min_port + 100
        if cmd_opts.use_port not in xrange(min_port, max_port+1):
            print "Error: port number should be in range [%d, %d])" % (min_port, max_port)
            sys.exit(1)
        args[useport_nam] = cmd_opts.use_port

    if cmd_opts.language is not None:
        langs = args["language_languages"] if "language_languages" in args else []
        if cmd_opts.language not in langs:
            print "Error: unsupported language: %s" % cmd_opts.language
            sys.exit(1)
        args[lang_nam] = cmd_opts.language

    # return arguments
    os.environ[config_var] = os.pathsep.join(dirs)
    #print "Args: ", args
    return args
Exemplo n.º 19
0
def get_env(theAdditionalOptions=None,
            appname=salomeappname,
            cfgname=salomecfgname,
            exeName=None):
    ###
    # Collect launch configuration files:
    # - The environment variable "<appname>Config" (SalomeAppConfig) which can
    #   define a list of directories (separated by ':' or ';' symbol) is checked
    # - If the environment variable "<appname>Config" is not set, only
    #   ${GUI_ROOT_DIR}/share/salome/resources/gui is inspected
    # - ${GUI_ROOT_DIR}/share/salome/resources/gui directory is always inspected
    #   so it is not necessary to put it in the "<appname>Config" variable
    # - The directories which are inspected are checked for files "<appname?salomeappname>.xml"
    #  (SalomeApp.xml) which define SALOME configuration
    # - These directories are analyzed beginning from the last one in the list,
    #   so the first directory listed in "<appname>Config" environment variable
    #   has higher priority: it means that if some configuration options
    #   is found in the next analyzed cofiguration file - it will be replaced
    # - The last configuration file which is parsed is user configuration file
    #   situated in the home directory (if it exists):
    #   * ~/.config/salome/.<appname>rc[.<version>]" for Linux (e.g. ~/.config/salome/.SalomeApprc.6.4.0)
    #   * ~/<appname>.xml[.<version>] for Windows (e.g. ~/SalomeApp.xml.6.4.0)
    # - Command line options have the highest priority and replace options
    #   specified in configuration file(s)
    ###

    if theAdditionalOptions is None:
        theAdditionalOptions = []

    global args
    config_var = appname + 'Config'

    # check KERNEL_ROOT_DIR
    kernel_root_dir = os.environ.get("KERNEL_ROOT_DIR", None)
    if kernel_root_dir is None:
        print """
        For each SALOME module, the environment variable <moduleN>_ROOT_DIR must be set.
        KERNEL_ROOT_DIR is mandatory.
        """
        sys.exit(1)

    ############################
    # parse command line options
    pars = CreateOptionParser(theAdditionalOptions, exeName=exeName)
    (cmd_opts, cmd_args) = pars.parse_args(sys.argv[1:])
    ############################

    # Process --print-port option
    if cmd_opts.print_port:
        from searchFreePort import searchFreePort
        searchFreePort({})
        print "port:%s" % (os.environ['NSPORT'])

        try:
            import PortManager
            PortManager.releasePort(os.environ['NSPORT'])
        except ImportError:
            pass

        sys.exit(0)
        pass

    # set resources variable SalomeAppConfig if it is not set yet
    dirs = []
    if os.getenv(config_var):
        if sys.platform == 'win32':
            dirs += re.split(os.pathsep, os.getenv(config_var))
        else:
            dirs += re.split('[;|:]', os.getenv(config_var))

    gui_available = False
    if os.getenv("GUI_ROOT_DIR"):
        gui_resources_dir = os.path.join(os.getenv("GUI_ROOT_DIR"), 'share',
                                         'salome', 'resources', 'gui')
        if os.path.isdir(gui_resources_dir):
            gui_available = True
            dirs.append(gui_resources_dir)
        pass
    if not gui_available:
        kernel_resources_dir = os.path.join(os.getenv("KERNEL_ROOT_DIR"),
                                            'bin', 'salome', 'appliskel')
        if os.getenv("KERNEL_ROOT_DIR") and os.path.isdir(
                kernel_resources_dir):
            dirs.append(kernel_resources_dir)
        pass
    os.environ[config_var] = os.pathsep.join(dirs)

    dirs.reverse(
    )  # reverse order, like in "path" variable - FILO-style processing

    try:
        dirs.remove(
            ''
        )  # to remove empty dirs if the variable terminate by ":" or if there are "::" inside
    except:
        pass

    _opts = {}  # associative array of options to be filled

    # parse SalomeApp.xml files in directories specified by SalomeAppConfig env variable
    for dir in dirs:
        filename = os.path.join(dir, appname + '.xml')
        if not os.path.exists(filename):
            if verbose():
                print "Configure parser: Warning : can not find configuration file %s" % filename
        else:
            try:
                p = xml_parser(filename, _opts, [])
                _opts = p.opts
            except:
                if verbose():
                    print "Configure parser: Error : can not read configuration file %s" % filename
            pass

    # parse user configuration file
    # It can be set via --resources=<file> command line option
    # or is given from default location (see defaultUserFile() function)
    # If user file for the current version is not found the nearest to it is used
    user_config = cmd_opts.resources
    if not user_config:
        user_config = userFile(appname, cfgname)
        if verbose():
            print "Configure parser: user configuration file is", user_config
    if not user_config or not os.path.exists(user_config):
        if verbose():
            print "Configure parser: Warning : can not find user configuration file"
    else:
        try:
            p = xml_parser(user_config, _opts, [])
            _opts = p.opts
        except:
            if verbose():
                print 'Configure parser: Error : can not read user configuration file'
            user_config = ""

    args = _opts

    args['user_config'] = user_config
    #print "User Configuration file: ", args['user_config']

    # set default values for options which are NOT set in config files
    for aKey in listKeys:
        if not args.has_key(aKey):
            args[aKey] = []

    for aKey in boolKeys:
        if not args.has_key(aKey):
            args[aKey] = 0

    if args[file_nam]:
        afile = args[file_nam]
        args[file_nam] = [afile]

    args[appname_nam] = appname

    # get the port number
    my_port = getPortNumber()

    args[port_nam] = my_port

    ####################################################
    # apply command-line options to the arguments
    # each option given in command line overrides the option from xml config file
    #
    # Options: gui, desktop, log_file, resources,
    #          xterm, modules, embedded, standalone,
    #          portkill, killall, interp, splash,
    #          catch_exceptions, pinter

    # GUI/Terminal, Desktop, Splash, STUDY_HDF
    args["session_gui"] = False
    args[batch_nam] = False
    args["study_hdf"] = None
    if cmd_opts.gui is not None:
        args[gui_nam] = cmd_opts.gui
    if cmd_opts.batch is not None:
        args[batch_nam] = True

    if not gui_available:
        args[gui_nam] = False

    if args[gui_nam]:
        args["session_gui"] = True
        if cmd_opts.desktop is not None:
            args["session_gui"] = cmd_opts.desktop
            args[splash_nam] = cmd_opts.desktop
        if args["session_gui"]:
            if cmd_opts.splash is not None:
                args[splash_nam] = cmd_opts.splash
    else:
        args["session_gui"] = False
        args[splash_nam] = False

    # Logger/Log file
    if cmd_opts.log_file is not None:
        if cmd_opts.log_file == 'CORBA':
            args[logger_nam] = True
        else:
            args[file_nam] = [cmd_opts.log_file]

    # Naming Service port log file
    if cmd_opts.ns_port_log_file is not None:
        args["ns_port_log_file"] = cmd_opts.ns_port_log_file

    # Study files
    for arg in cmd_args:
        if arg[-4:] == ".hdf" and not args["study_hdf"]:
            args["study_hdf"] = arg

    # Python scripts
    from salomeContextUtils import getScriptsAndArgs, ScriptAndArgs
    args[script_nam] = getScriptsAndArgs(cmd_args)
    if args[gui_nam] and args["session_gui"]:
        new_args = []
        for sa_obj in args[
                script_nam]:  # args[script_nam] is a list of ScriptAndArgs objects
            script = re.sub(r'^python.*\s+', r'', sa_obj.script)
            new_args.append(
                ScriptAndArgs(script=script, args=sa_obj.args, out=sa_obj.out))
        #
        args[script_nam] = new_args

    # xterm
    if cmd_opts.xterm is not None: args[xterm_nam] = cmd_opts.xterm

    # Modules
    if cmd_opts.modules is not None:
        args[modules_nam] = []
        listlist = cmd_opts.modules
        for listi in listlist:
            args[modules_nam] += re.split("[:;,]", listi)
    else:
        # if --modules (-m) command line option is not given
        # try SALOME_MODULES environment variable
        if os.getenv("SALOME_MODULES"):
            args[modules_nam] = re.split("[:;,]", os.getenv("SALOME_MODULES"))
            pass

    # Embedded
    if cmd_opts.embedded is not None:
        args[embedded_nam] = filter(lambda a: a.strip(),
                                    re.split("[:;,]", cmd_opts.embedded))

    # Standalone
    if cmd_opts.standalone is not None:
        args[standalone_nam] = filter(lambda a: a.strip(),
                                      re.split("[:;,]", cmd_opts.standalone))

    # Normalize the '--standalone' and '--embedded' parameters
    standalone, embedded = process_containers_params(args.get(standalone_nam),
                                                     args.get(embedded_nam))
    if standalone is not None:
        args[standalone_nam] = standalone
    if embedded is not None:
        args[embedded_nam] = embedded

    # Kill
    if cmd_opts.portkill is not None: args[portkill_nam] = cmd_opts.portkill
    if cmd_opts.killall is not None: args[killall_nam] = cmd_opts.killall

    # Interpreter
    if cmd_opts.interp is not None:
        args[interp_nam] = cmd_opts.interp

    # Exceptions
    if cmd_opts.catch_exceptions is not None:
        args[except_nam] = not cmd_opts.catch_exceptions

    # Relink config file
    if cmd_opts.save_config is not None:
        args['save_config'] = cmd_opts.save_config

    # Interactive python console
    if cmd_opts.pinter is not None:
        args[pinter_nam] = cmd_opts.pinter

    # Gdb session in xterm
    if cmd_opts.gdb_session is not None:
        args[gdb_session_nam] = cmd_opts.gdb_session

    # Ddd session in xterm
    if cmd_opts.ddd_session is not None:
        args[ddd_session_nam] = cmd_opts.ddd_session

    # valgrind session
    if cmd_opts.valgrind_session is not None:
        args[valgrind_session_nam] = cmd_opts.valgrind_session

    # Shutdown servers
    if cmd_opts.shutdown_servers is None:
        args[shutdown_servers_nam] = 0
    else:
        args[shutdown_servers_nam] = cmd_opts.shutdown_servers
        pass

    # Foreground
    if cmd_opts.foreground is None:
        args[foreground_nam] = 1
    else:
        args[foreground_nam] = cmd_opts.foreground
        pass

    # wake up session
    if cmd_opts.wake_up_session is not None:
        args[wake_up_session_nam] = cmd_opts.wake_up_session

    ####################################################
    # Add <theAdditionalOptions> values to args
    for add_opt in theAdditionalOptions:
        cmd = "args[\"{0}\"] = cmd_opts.{0}".format(add_opt.dest)
        exec(cmd)
    ####################################################

    # disable signals handling
    if args[except_nam] == 1:
        os.environ["NOT_INTERCEPT_SIGNALS"] = "1"
        pass

    # now modify SalomeAppConfig environment variable
    # to take into account the SALOME modules
    if os.sys.platform == 'win32':
        dirs = re.split('[;]', os.environ[config_var])
    else:
        dirs = re.split('[;|:]', os.environ[config_var])
    for module in args[modules_nam]:
        if module not in ["KERNEL", "GUI", ""] and os.getenv(
                "{0}_ROOT_DIR".format(module)):
            d1 = os.path.join(os.getenv("{0}_ROOT_DIR".format(module)),
                              "share", "salome", "resources", module.lower())
            d2 = os.path.join(os.getenv("{0}_ROOT_DIR".format(module)),
                              "share", "salome", "resources")
            #if os.path.exists( "%s/%s.xml"%(d1, appname) ):
            if os.path.exists(os.path.join(d1,
                                           "{0}.xml".format(salomeappname))):
                dirs.append(d1)
            #elif os.path.exists( "%s/%s.xml"%(d2, appname) ):
            elif os.path.exists(
                    os.path.join(d2, "{0}.xml".format(salomeappname))):
                dirs.append(d2)
        else:
            #print "* '"+m+"' should be deleted from ",args[modules_nam]
            pass

    # Test
    if cmd_opts.test_script_file is not None:
        args[test_nam] = []
        filename = cmd_opts.test_script_file
        args[test_nam] += re.split("[:;,]", filename)

    # Play
    if cmd_opts.play_script_file is not None:
        args[play_nam] = []
        filename = cmd_opts.play_script_file
        args[play_nam] += re.split("[:;,]", filename)

    # Server launch command
    if cmd_opts.server_launch_mode is not None:
        args["server_launch_mode"] = cmd_opts.server_launch_mode

    # Server launch command
    if cmd_opts.use_port is not None:
        min_port = 2810
        max_port = min_port + 100
        if cmd_opts.use_port not in xrange(min_port, max_port + 1):
            print "Error: port number should be in range [%d, %d])" % (
                min_port, max_port)
            sys.exit(1)
        args[useport_nam] = cmd_opts.use_port

    if cmd_opts.language is not None:
        langs = args[
            "language_languages"] if "language_languages" in args else []
        if cmd_opts.language not in langs:
            print "Error: unsupported language: %s" % cmd_opts.language
            sys.exit(1)
        args[lang_nam] = cmd_opts.language

    # return arguments
    os.environ[config_var] = os.pathsep.join(dirs)
    #print "Args: ", args
    return args
Exemplo n.º 20
0
 def wrapper(self, *args, **kwargs):
     from salome_utils import verbose
     if verbose():
         function(self, *args, **kwargs)