예제 #1
0
def run_autovnv_command(_c, _log, pythondir=None):
    """
    Run command with arguments.
    Redirection of the stdout or stderr of the command.
    """
    assert type(_c) == str or type(_c) == unicode

    log.debug("run_autovnv_command: %s" % _c)

    try:
        _log.seek(0, os.SEEK_END)
    except:
        _log.seek(0, 2)

    def __text(_t):
        return "\n\nExecution failed --> %s: %s" \
                "\n - command: %s"                \
                "\n - directory: %s\n\n" %        \
                (_t, str(retcode), _c, os.getcwd())

    _l = ""

    cmd = separate_args(_c)

    env = os.environ.copy()

    if pythondir:
        pythondir = enquote_arg(pythondir)
        pythonpath = pythondir + ':' + env.get("PYTHONPATH", '')
        env.update([("PYTHONPATH", pythonpath)])

    try:
        t1 = time.time()
        retcode = run_command(cmd, stdout=_log, stderr=_log, env=env)
        t2 = time.time()

        if retcode < 0:
            _l = __text("command was terminated by signal")
        elif retcode > 0:
            _l = __text("command return")

    except OSError:
        import traceback
        import sys
        exc_info = sys.exc_info()
        bt = traceback.format_exception(*exc_info)
        for l in bt:
            _log.write(l)
        retcode = 0
        del exc_info
        _l = __text("unknown command")
        t1 = 0.
        t2 = 0.

    _log.flush()
    if _l:
        _log.write(_l)

    return retcode, "%.2f" % (t2 - t1)
예제 #2
0
def main(argv, pkg):
    """
    Main function.
    """

    template = """\
%(salomeenv)s
CFDSTUDY_ROOT_DIR=%(prefix)s
PYTHONPATH=%(pythondir)s/salome:%(pkgpythondir)s${PYTHONPATH:+:$PYTHONPATH}
export CFDSTUDY_ROOT_DIR PYTHONPATH
%(runsalome)s --modules=%(modules)s
"""

    if pkg.config.have_salome == "no":
        sys.stderr.write("SALOME is not available in this installation.\n")
        sys.exit(1)

    # Skipped modules: YACS,JOBMANAGER,HOMARD,OPENTURNS
    default_modules = "GEOM,SMESH,MED,CFDSTUDY,PARAVIS"

    run_cmd = pkg.config.salome_run
    if not run_cmd:
        run_cmd = "${KERNEL_ROOT_DIR}/bin/salome/envSalome.py python ${KERNEL_ROOT_DIR}/bin/salome/runSalome.py"

    path = pkg.get_dir('pkgpythondir')
    path = path + ":" + pkg.get_dir('pythondir')
    if pkg.name == 'neptune_cfd':
        cspath = os.path.join(pkg.get_dir('pythondir'), 'code_saturne')
        path = path + ":" + cspath

    # Test if EOS modules could be imported
    if pkg.config.libs['eos'].have == "yes":
        eosprefix = pkg.config.libs['eos'].prefix
        try:
            from distutils import sysconfig
            eospath = os.path.join(
                sysconfig.get_python_lib(0, 0, prefix=eosprefix), 'eos')
        except Exception:
            eospath = ''
        if eospath:
            if os.path.isdir(eospath) and not eospath in sys.path:
                path = path + ":" + eospath

    prefix = pkg.get_dir('prefix')
    pythondir = pkg.get_dir('pythondir')
    cmd = template % {
        'salomeenv': pkg.config.salome_env,
        'prefix': prefix,
        'pythondir': pythondir,
        'pkgpythondir': path,
        'runsalome': run_cmd,
        'modules': default_modules
    }

    process_cmd_line(argv, pkg)

    retcode = cs_exec_environment.run_command(cmd, stdout=None, stderr=None)
예제 #3
0
def link_build(pkg, install=False, destdir=None):
    """
    Link function for build process.
    """
    retval = 0

    # Determine executable name

    exec_name = pkg.solver
    if install:
        exec_name = os.path.join(pkg.dirs['pkglibexecdir'][1], exec_name)
        # Strangely, on MinGW, Windows paths are not correctly handled here...
        # So, assuming we always build on MinGW, here is a little trick!
        if sys.platform.startswith("win"):
            if pkg.get_cross_compil() != 'cygwin':  #mingw32 or mingw64
                exec_name = os.path.normpath('C:\\MinGW\\msys\\1.0' +
                                             exec_name)
            else:
                exec_name = pkg.dirs['pkglibexecdir'][1] + "/" + pkg.solver
        if destdir:
            exec_name = dest_subdir(destdir, exec_name)
        dirname = os.path.dirname(exec_name)
        if not os.path.exists(dirname):
            os.makedirs(dirname)

    print("Linking executable: " + exec_name)

    # Find files to compile in source path

    p_libs = get_flags(pkg, 'libs', link_build=True)

    cmd = [get_compiler(pkg, 'ld', link_build=True)]
    cmd = cmd + ["-o", exec_name]
    cmd = cmd + get_build_flags(pkg, 'ldflags', install, destdir)

    # If present, address sanitizer needs to come first
    if '-lasan' in p_libs:
        p_libs.remove('-lasan')
        cmd += ['-lasan']

    cmd = cmd + p_libs
    if pkg.config.rpath != "":
        cmd += so_dirs_path(cmd, pkg)
    if run_command(cmd, pkg=pkg, echo=True) != 0:
        retval = 1

    return retval
예제 #4
0
def main(argv, pkg):
    """
    Main function.
    """

    options, args = process_cmd_line(argv, pkg)

    if not args:
        return 1

    cmd = [pkg.get_io_dump(), '--diff']
    cmd += argv

    # Set environment modules if present

    cs_exec_environment.set_modules(pkg)
    cs_exec_environment.source_rcfile(pkg)

    # Run executable

    return cs_exec_environment.run_command(cmd)
예제 #5
0
def main(argv, pkg):
    """
    Main function.
    """

    options, args = process_cmd_line(argv, pkg)

    if not args:
        return 1

    cmd = [pkg.get_io_dump(), '--diff']
    cmd += argv

    # Set environment modules if present

    cs_exec_environment.set_modules(pkg)
    cs_exec_environment.source_rcfile(pkg)

    # Run executable

    return cs_exec_environment.run_command(cmd)
예제 #6
0
def link_build(pkg, install=False, destdir=None):
    """
    Link function for build process.
    """
    retval = 0

    # Determine executable name

    exec_name = pkg.solver
    if install:
        exec_name = os.path.join(pkg.dirs['pkglibexecdir'][1], exec_name)
        # Strangely, on MinGW, Windows paths are not correctly handled here...
        # So, assuming we always build on MinGW, here is a little trick!
        if sys.platform.startswith("win"):
            if pkg.get_cross_compil() != 'cygwin': #mingw32 or mingw64
                exec_name = os.path.normpath('C:\\MinGW\\msys\\1.0' + exec_name)
            else:
                exec_name = pkg.dirs['pkglibexecdir'][1] + "/" + pkg.solver
        if destdir:
            exec_name = dest_subdir(destdir, exec_name)
        dirname = os.path.dirname(exec_name)
        if not os.path.exists(dirname):
            os.makedirs(dirname)

    print("Linking executable: " + exec_name)

    # Find files to compile in source path

    p_libs = get_flags(pkg, 'libs', link_build = True)

    cmd = [get_compiler(pkg, 'ld', link_build = True)]
    cmd = cmd + ["-o", exec_name]
    cmd = cmd + get_build_flags(pkg, 'ldflags', install, destdir)
    cmd = cmd + p_libs
    if pkg.config.rpath != "":
        cmd += so_dirs_path(cmd, pkg)
    if run_command(cmd, pkg=pkg, echo=True) != 0:
        retval = 1

    return retval
예제 #7
0
    def preprocess(self):
        """
        Runs the preprocessor in the execution directory
        """

        if self.mesh_input:
            return

        # Study directory
        study_dir = os.path.split(self.case_dir)[0]

        # User config file
        u_cfg = configparser.ConfigParser()
        u_cfg.read(self.package.get_user_configfile())

        # Global config file
        g_cfg = configparser.ConfigParser()
        g_cfg.read(self.package.get_global_configfile())

        # A mesh can be found in different mesh database directories
        # (case, study, user, global -- in this order)
        mesh_dirs = []
        if self.mesh_dir is not None:
            mesh_dir = os.path.expanduser(self.mesh_dir)
            if not os.path.isabs(mesh_dir):
                mesh_dir = os.path.join(self.case_dir, mesh_dir)
            mesh_dirs.append(mesh_dir)
        if os.path.isdir(os.path.join(study_dir, 'MESH')):
            mesh_dirs.append(os.path.join(study_dir, 'MESH'))
        if u_cfg.has_option('run', 'meshdir'):
            add_path = u_cfg.get('run', 'meshdir').split(':')
            for d in add_path:
                mesh_dirs.append(d)
        if g_cfg.has_option('run', 'meshdir'):
            add_path = g_cfg.get('run', 'meshdir').split(':')
            for d in add_path:
                mesh_dirs.append(d)

        # Switch to execution directory

        cur_dir = os.path.realpath(os.getcwd())
        if cur_dir != self.exec_dir:
            os.chdir(self.exec_dir)

        mesh_id = None

        if len(self.meshes) > 1:
            mesh_id = 0
            destdir = 'mesh_input'
            make_clean_dir(destdir)

        # Run once per mesh

        for m in self.meshes:

            # Get absolute mesh paths

            if m is None:
                err_str = 'Preprocessing stage required but no mesh is given'
                raise RunCaseError(err_str)

            if (type(m) == tuple):
                m0 = m[0]
            else:
                m0 = m

            m0 = os.path.expanduser(m0)

            mesh_path = m0
            if (not os.path.isabs(m0)) and len(mesh_dirs) > 0:
                for mesh_dir in mesh_dirs:
                    mesh_path = os.path.join(mesh_dir, m0)
                    if os.path.isfile(mesh_path):
                        break

            if not os.path.isfile(mesh_path):
                err_str = 'Mesh file ' + m0 + ' not found'
                if not (os.path.isabs(mesh_path) or mesh_dirs):
                    err_str += '(no mesh directory given)'
                raise RunCaseError(err_str)

            # Build command

            cmd = [self.package.get_preprocessor()]

            if (type(m) == tuple):
                for opt in m[1:]:
                    cmd.append(opt)

            if (mesh_id != None):
                mesh_id += 1
                cmd = cmd + ['--log', 'preprocessor_%02d.log' % (mesh_id)]
                cmd = cmd + [
                    '--out',
                    os.path.join('mesh_input', 'mesh_%02d' % (mesh_id))
                ]
            else:
                cmd = cmd + ['--log']
                cmd = cmd + ['--out', 'mesh_input']

            cmd.append(mesh_path)

            # Run command

            retcode = run_command(cmd, pkg=self.package)

            if retcode != 0:
                err_str = \
                    'Error running the preprocessor.\n' \
                    'Check the preprocessor.log file for details.\n\n'
                sys.stderr.write(err_str)

                self.exec_solver = False

                self.error = 'preprocess'

                break

        # Revert to initial directory

        if cur_dir != self.exec_dir:
            os.chdir(cur_dir)

        return retcode
예제 #8
0
def compile_and_link(pkg, srcdir, destdir,
                     opt_cflags=None, opt_cxxflags=None, opt_fcflags=None,
                     opt_libs=None, force_link=False, keep_going=False,
                     stdout = sys.stdout, stderr = sys.stderr):
    """
    Compilation and link function.
    """
    retval = 0

    # Determine executable name

    exec_name = pkg.solver
    if destdir != None:
        exec_name = os.path.join(destdir, exec_name)

    # Change to temporary directory

    call_dir = os.getcwd()
    temp_dir = tempfile.mkdtemp(suffix=".cs_compile")
    os.chdir(temp_dir)

    # Find files to compile in source path

    dir_files = os.listdir(srcdir)

    c_files = fnmatch.filter(dir_files, '*.c')
    h_files = fnmatch.filter(dir_files, '*.h')
    cxx_files = fnmatch.filter(dir_files, '*.cxx') + fnmatch.filter(dir_files, '*.cpp')
    hxx_files = fnmatch.filter(dir_files, '*.hxx') + fnmatch.filter(dir_files, '*.hpp')
    f_files = fnmatch.filter(dir_files, '*.[fF]90')

    # Special handling for some linkers (such as Mac OS X), for which
    # no multiple definitions are allowable in static mode;
    # in this case, extract archive, then overwrite with user files.

    p_libs = get_flags(pkg, 'libs')
    if pkg.config.special_user_link == 'ar_x':
        if force_link or (len(c_files) + len(cxx_files) + len(f_files)) > 0:
            lib0 = os.path.join(pkg.get_dir('libdir'),
                                'lib' + p_libs[0][2:] + '.a')
            p_libs = p_libs[1:]
            cmd = ['ar', 'x', lib0]
            if run_command(cmd, pkg=pkg, echo=True,
                           stdout=stdout, stderr=stderr) != 0:
                retval = 1

    # Compile files

    for f in c_files:
        if (retval != 0 and not keep_going):
            break
        cmd = [get_compiler(pkg, 'cc')]
        if opt_cflags != None:
            cmd = cmd + separate_args(opt_cflags)
        if len(h_files) > 0:
            cmd = cmd + ["-I", srcdir]
        cmd.append('-DHAVE_CONFIG_H')
        if f == 'cs_base.c':
            cmd = cmd + ['-DLOCALEDIR=\\"' + pkg.get_dir('localedir') + '\\"', \
                         '-DPKGDATADIR=\\"' + pkg.get_dir('pkgdatadir') + '\\"']
        cmd = cmd + get_flags(pkg, 'cppflags')
        cmd = cmd + separate_args(pkg.config.flags['cflags'])
        cmd = cmd + ["-c", os.path.join(srcdir, f)]
        if run_command(cmd, pkg=pkg, echo=True,
                       stdout=stdout, stderr=stderr) != 0:
            retval = 1

    for f in cxx_files:
        if (retval != 0 and not keep_going):
            break
        cmd = [get_compiler(pkg, 'cxx')]
        if opt_cxxflags != None:
            cmd = cmd + separate_args(opt_cxxflags)
        if len(hxx_files) > 0:
            cmd = cmd + ["-I", srcdir]
        cmd.append('-DHAVE_CONFIG_H')
        cmd = cmd + get_flags(pkg, 'cppflags')
        cmd = cmd + separate_args(pkg.config.flags['cxxflags'])
        cmd = cmd + ["-c", os.path.join(srcdir, f)]
        if run_command(cmd, pkg=pkg, echo=True,
                       stdout=stdout, stderr=stderr) != 0:
            retval = 1

    user_mod_name = 'cs_user_modules.f90'
    if user_mod_name in f_files:
        f_files.remove(user_mod_name)
        f_files.insert(0, user_mod_name)

    for f in f_files:
        if (retval != 0 and not keep_going):
            break
        cmd = [get_compiler(pkg, 'fc')]
        if f == 'cs_user_parameters.f90':
            cmd = cmd + ["-o", "cs_f_user_parameters.o"]
        if f == 'cs_user_extra_operations.f90':
            cmd = cmd + ["-o", "cs_f_user_extra_operations.o"]
        if opt_fcflags != None:
            cmd = cmd + separate_args(opt_fcflags)
        cmd = cmd + ["-I", srcdir]
        if pkg.config.fcmodinclude != "-I":
            cmd = cmd + [pkg.config.fcmodinclude, srcdir]
        cmd = cmd + ["-I", pkg.get_dir('pkgincludedir')]
        if pkg.config.fcmodinclude != "-I":
            cmd = cmd + [pkg.config.fcmodinclude, pkg.get_dir('pkgincludedir')]
        cmd = cmd + separate_args(pkg.config.flags['fcflags'])
        cmd = cmd + ["-c", os.path.join(srcdir, f)]
        if run_command(cmd, pkg=pkg, echo=True,
                       stdout=stdout, stderr=stderr) != 0:
            retval = 1

    if retval == 0 and (force_link or (len(c_files) + len(cxx_files) + len(f_files)) > 0):
        cmd = [get_compiler(pkg, 'ld')]
        cmd = cmd + ["-o", exec_name]
        if (len(c_files) + len(cxx_files) + len(f_files)) > 0:
            dir_files = os.listdir(temp_dir)
            o_files = fnmatch.filter(dir_files, '*.o')
            cmd = cmd + o_files
        if opt_libs != None:
            if len(opt_libs) > 0:
                cmd += separate_args(opt_libs)
        cmd = cmd + get_flags(pkg, 'ldflags')
        cmd = cmd + p_libs
        if pkg.config.rpath != "":
            cmd += so_dirs_path(cmd, pkg)
        if run_command(cmd, pkg=pkg, echo=True,
                       stdout=stdout, stderr=stderr) != 0:
            retval = 1

    # Cleanup

    for f in os.listdir(temp_dir):
        os.remove(os.path.join(temp_dir, f))

    # Return to original directory

    os.chdir(call_dir)
    os.rmdir(temp_dir)

    return retval
예제 #9
0
    def preprocess(self):
        """
        Runs the preprocessor in the execution directory
        """

        if self.mesh_input:
            return

        # Study directory
        study_dir = os.path.split(self.case_dir)[0]

        # User config file
        u_cfg = configparser.ConfigParser()
        u_cfg.read(self.package.get_user_configfile())

        # Global config file
        g_cfg = configparser.ConfigParser()
        g_cfg.read(self.package.get_global_configfile())

        # A mesh can be found in different mesh database directories
        # (case, study, user, global -- in this order)
        mesh_dirs = []
        if self.mesh_dir is not None:
            mesh_dir = os.path.expanduser(self.mesh_dir)
            if not os.path.isabs(mesh_dir):
                mesh_dir = os.path.join(self.case_dir, mesh_dir)
            mesh_dirs.append(mesh_dir)
        if os.path.isdir(os.path.join(study_dir, 'MESH')):
            mesh_dirs.append(os.path.join(study_dir, 'MESH'))
        if u_cfg.has_option('run', 'meshdir'):
            add_path = u_cfg.get('run', 'meshdir').split(':')
            for d in add_path:
                mesh_dirs.append(d)
        if g_cfg.has_option('run', 'meshdir'):
            add_path = g_cfg.get('run', 'meshdir').split(':')
            for d in add_path:
                mesh_dirs.append(d)

        # Switch to execution directory

        cur_dir = os.path.realpath(os.getcwd())
        if cur_dir != self.exec_dir:
            os.chdir(self.exec_dir)

        mesh_id = None

        if len(self.meshes) > 1:
            mesh_id = 0
            destdir = 'mesh_input'
            if not os.path.isdir(destdir):
                os.mkdir(destdir)
            else:
                list = os.listdir(destdir)
                for f in list:
                    os.remove(os.path.join(destdir,f))

        # Run once per mesh

        for m in self.meshes:

            # Get absolute mesh paths

            if m is None:
                err_str = 'Preprocessing stage required but no mesh is given'
                raise RunCaseError(err_str)

            if (type(m) == tuple):
                m0 = m[0]
            else:
                m0 = m

            m0 = os.path.expanduser(m0)

            mesh_path = m0
            if (not os.path.isabs(m0)) and len(mesh_dirs) > 0:
                for mesh_dir in mesh_dirs:
                    mesh_path = os.path.join(mesh_dir, m0)
                    if os.path.isfile(mesh_path):
                        break

            if not os.path.isfile(mesh_path):
                err_str = 'Mesh file ' + m0 + ' not found'
                if not (os.path.isabs(mesh_path) or mesh_dirs):
                    err_str += '(no mesh directory given)'
                raise RunCaseError(err_str)

            # Build command

            cmd = [self.package.get_preprocessor()]

            if (type(m) == tuple):
                for opt in m[1:]:
                    cmd.append(opt)

            if (mesh_id != None):
                mesh_id += 1
                cmd = cmd + ['--log', 'preprocessor_%02d.log' % (mesh_id)]
                cmd = cmd + ['--out', os.path.join('mesh_input',
                                                   'mesh_%02d' % (mesh_id))]
            else:
                cmd = cmd + ['--log']
                cmd = cmd + ['--out', 'mesh_input']

            cmd.append(mesh_path)

            # Run command

            retcode = run_command(cmd, pkg=self.package)

            if retcode != 0:
                err_str = \
                    'Error running the preprocessor.\n' \
                    'Check the preprocessor.log file for details.\n\n'
                sys.stderr.write(err_str)

                self.exec_solver = False

                self.error = 'preprocess'

                break

        # Revert to initial directory

        if cur_dir != self.exec_dir:
            os.chdir(cur_dir)

        return retcode
예제 #10
0
    def slotBatchRunning(self):
        """
        Launch Code_Saturne batch running.
        """
        # Is the file saved?

        if self.case['new'] == "yes" or len(self.case['undo']) > 0 or len(self.case['redo']) > 0:

            title = self.tr("Warning")
            msg   = self.tr("The current case must be saved before "\
                            "running the ") + self.tr(self.case['package']).code_name + self.tr(" script.")
            QMessageBox.information(self, title, msg)
            return

        # Ensure code is run from a case subdirectory

        prv_dir = os.getcwd()
        os.chdir(self.case['scripts_path'])

        # Do we have a mesh ?

        have_mesh = False
        node_ecs = self.case.xmlGetNode('solution_domain')
        if node_ecs.xmlGetNode('meshes_list'):
            if node_ecs.xmlGetNode('meshes_list').xmlGetNodeList('mesh'):
                have_mesh = True
        if node_ecs.xmlGetNode('mesh_input', 'path'):
            have_mesh = True
        if not have_mesh:
            title = self.tr("Warning")
            msg   = self.tr("You have to select a mesh.\n\n")
            QMessageBox.information(self, title, msg)
            return

        # Verify if boundary condition definitions exist

        bd = LocalizationModel('BoundaryZone', self.case)
        if not bd.getZones():
            if self.case['no_boundary_conditions'] == False:
                title = self.tr("Warning")
                msg   = self.tr("No boundary definition declared.\n\n")
                QMessageBox.warning(self, title, msg)
                self.case['no_boundary_conditions'] = True

        # Build command line

        key = self.case['batch_type']

        batch = cs_exec_environment.enquote_arg(self.case['runcase'].path)

        if key == None:
            run_id, run_title = self.__suggest_run_id()
            self.__updateRuncase(run_id)
            cmd = batch
            key = 'localhost'
        elif key[0:3] == 'CCC':
            cmd = 'msub ' + batch
        elif key[0:5] == 'LOADL':
            cmd = 'llsubmit ' + batch
        elif key[0:3] == 'LSF':
            cmd = 'bsub < ' + batch
        elif key[0:3] == 'PBS' or key[0:3] == 'SGE':
            cmd = 'qsub ' + batch
        elif key[0:5] == 'SLURM':
            cmd = 'sbatch ' + batch
        else:
            pass

        if self.case['salome'] or key == 'localhost':
            dlg = ListingDialogView(self.parent, self.case, run_title, cmd)
            dlg.show()
        else:
            cs_exec_environment.run_command(cmd)

        if self.case['salome'] or key == 'localhost':
            self.__updateRuncase('')  # remove --id <id> from runcase

        os.chdir(prv_dir)
예제 #11
0
def main(argv, pkg):
    """
    Main function.
    """

    template = """\
%(salomeenv)s
CFDSTUDY_ROOT_DIR=%(prefix)s
PYTHONPATH=%(pythondir)s/salome:%(pkgpythondir)s${PYTHONPATH:+:$PYTHONPATH}
export CFDSTUDY_ROOT_DIR PYTHONPATH
%(runsalome)s --modules=%(modules)s
"""

    if pkg.config.have_salome == "no":
        sys.stderr.write("SALOME is not available in this installation.\n")
        sys.exit(1)

    # Skipped modules (version 6.3.0): YACS,JOBMANAGER,HOMARD,OPENTURNS
    default_modules = "GEOM,SMESH,MED,CFDSTUDY,PARAVIS,VISU"

    run_cmd = pkg.config.salome_run
    if not run_cmd:
        run_cmd = "${KERNEL_ROOT_DIR}/bin/salome/envSalome.py python ${KERNEL_ROOT_DIR}/bin/salome/runSalome.py"

    path = pkg.get_dir('pkgpythondir')
    path = path+":"+pkg.get_dir('pythondir')
    if pkg.name == 'neptune_cfd':
        cspath = os.path.join(pkg.get_dir('csdir'), "lib",
                                                   "python" + sys.version[:3],
                                                   "site-packages", "code_saturne")
        path = path+":"+cspath

        # Test if EOS modules could be imported
        if pkg.config.libs['eos'].have == "yes":
            eosprefix = pkg.config.libs['eos'].prefix
            try:
                from distutils import sysconfig
                eospath = os.path.join(sysconfig.get_python_lib(0, 0, prefix=eosprefix), 'eos')
            except Exception:
                eospath = ''
            if eospath:
                if os.path.isdir(eospath) and not eospath in sys.path:
                    path = path+":"+eospath

    if pkg.name == 'neptune_cfd':
        prefix = pkg.get_dir('csdir')
        pythondir = pkg.get_dir('cspythondir')
    else:
        prefix = pkg.get_dir('prefix')
        pythondir = pkg.get_dir('pythondir')
    cmd = template % {'salomeenv': pkg.config.salome_env,
                      'prefix': prefix,
                      'pythondir': pythondir,
                      'pkgpythondir': path,
                      'runsalome': run_cmd,
                      'modules': default_modules}

    process_cmd_line(argv, pkg)

    retcode = cs_exec_environment.run_command(cmd,
                                              stdout=None,
                                              stderr=None)
예제 #12
0
def compile_and_link(pkg,
                     srcdir,
                     destdir,
                     opt_cflags=None,
                     opt_cxxflags=None,
                     opt_fcflags=None,
                     opt_libs=None,
                     force_link=False,
                     keep_going=False,
                     stdout=sys.stdout,
                     stderr=sys.stderr):
    """
    Compilation and link function.
    """
    retval = 0

    # Determine executable name

    exec_name = pkg.solver
    if destdir != None:
        exec_name = os.path.join(destdir, exec_name)

    # Change to temporary directory

    call_dir = os.getcwd()
    temp_dir = tempfile.mkdtemp(suffix=".cs_compile")
    os.chdir(temp_dir)

    # Find files to compile in source path

    dir_files = os.listdir(srcdir)

    c_files = fnmatch.filter(dir_files, '*.c')
    h_files = fnmatch.filter(dir_files, '*.h')
    cxx_files = fnmatch.filter(dir_files, '*.cxx') + fnmatch.filter(
        dir_files, '*.cpp')
    hxx_files = fnmatch.filter(dir_files, '*.hxx') + fnmatch.filter(
        dir_files, '*.hpp')
    f_files = fnmatch.filter(dir_files, '*.[fF]90')

    # Special handling for some linkers (such as Mac OS X), for which
    # no multiple definitions are allowable in static mode;
    # in this case, extract archive, then overwrite with user files.

    p_libs = get_flags(pkg, 'libs')
    if pkg.config.special_user_link == 'ar_x':
        if force_link or (len(c_files) + len(cxx_files) + len(f_files)) > 0:
            lib0 = os.path.join(pkg.get_dir('libdir'),
                                'lib' + p_libs[0][2:] + '.a')
            p_libs = p_libs[1:]
            cmd = ['ar', 'x', lib0]
            if run_command(
                    cmd, pkg=pkg, echo=True, stdout=stdout,
                    stderr=stderr) != 0:
                retval = 1

    # Compile files

    for f in c_files:
        if (retval != 0 and not keep_going):
            break
        cmd = [get_compiler(pkg, 'cc')]
        if opt_cflags != None:
            cmd = cmd + separate_args(opt_cflags)
        if len(h_files) > 0:
            cmd = cmd + ["-I", srcdir]
        cmd.append('-DHAVE_CONFIG_H')
        if f == 'cs_base.c':
            cmd = cmd + ['-DLOCALEDIR=\\"' + pkg.get_dir('localedir') + '\\"', \
                         '-DPKGDATADIR=\\"' + pkg.get_dir('pkgdatadir') + '\\"']
        cmd = cmd + get_flags(pkg, 'cppflags')
        cmd = cmd + separate_args(pkg.config.flags['cflags'])
        cmd = cmd + ["-c", os.path.join(srcdir, f)]
        if run_command(cmd, pkg=pkg, echo=True, stdout=stdout,
                       stderr=stderr) != 0:
            retval = 1

    for f in cxx_files:
        if (retval != 0 and not keep_going):
            break
        cmd = [get_compiler(pkg, 'cxx')]
        if opt_cxxflags != None:
            cmd = cmd + separate_args(opt_cxxflags)
        if len(hxx_files) > 0:
            cmd = cmd + ["-I", srcdir]
        cmd.append('-DHAVE_CONFIG_H')
        cmd = cmd + get_flags(pkg, 'cppflags')
        cmd = cmd + separate_args(pkg.config.flags['cxxflags'])
        cmd = cmd + ["-c", os.path.join(srcdir, f)]
        if run_command(cmd, pkg=pkg, echo=True, stdout=stdout,
                       stderr=stderr) != 0:
            retval = 1

    user_mod_name = 'cs_user_modules.f90'
    if user_mod_name in f_files:
        f_files.remove(user_mod_name)
        f_files.insert(0, user_mod_name)

    for f in f_files:
        if (retval != 0 and not keep_going):
            break
        cmd = [get_compiler(pkg, 'fc')]
        if f == 'cs_user_boundary_conditions.f90':
            cmd = cmd + ["-o", "cs_f_user_boundary_conditions.o"]
        if f == 'cs_user_parameters.f90':
            cmd = cmd + ["-o", "cs_f_user_parameters.o"]
        if f == 'cs_user_extra_operations.f90':
            cmd = cmd + ["-o", "cs_f_user_extra_operations.o"]
        if f == 'cs_user_initialization.f90':
            cmd = cmd + ["-o", "cs_f_user_initialization.o"]
        if f == 'cs_user_physical_properties.f90':
            cmd = cmd + ["-o", "cs_f_user_physical_properties.o"]
        if opt_fcflags != None:
            cmd = cmd + separate_args(opt_fcflags)
        cmd = cmd + ["-I", srcdir]
        if pkg.config.fcmodinclude != "-I":
            cmd = cmd + [pkg.config.fcmodinclude, srcdir]
        cmd = cmd + ["-I", pkg.get_dir('pkgincludedir')]
        if pkg.config.fcmodinclude != "-I":
            cmd = cmd + [pkg.config.fcmodinclude, pkg.get_dir('pkgincludedir')]
        cmd = cmd + separate_args(pkg.config.flags['fcflags'])
        cmd = cmd + ["-c", os.path.join(srcdir, f)]
        if run_command(cmd, pkg=pkg, echo=True, stdout=stdout,
                       stderr=stderr) != 0:
            retval = 1

    if retval == 0 and (force_link or
                        (len(c_files) + len(cxx_files) + len(f_files)) > 0):
        cmd = [get_compiler(pkg, 'ld')]
        cmd = cmd + ["-o", exec_name]
        if (len(c_files) + len(cxx_files) + len(f_files)) > 0:
            dir_files = os.listdir(temp_dir)
            o_files = fnmatch.filter(dir_files, '*.o')
            cmd = cmd + o_files
        # If present, address sanitizer needs to come first
        if '-lasan' in p_libs:
            p_libs.remove('-lasan')
            cmd += ['-lasan']
        if opt_libs != None:
            if len(opt_libs) > 0:
                cmd += separate_args(opt_libs)
        cmd = cmd + get_flags(pkg, 'ldflags')
        cmd = cmd + p_libs
        if pkg.config.rpath != "":
            cmd += so_dirs_path(cmd, pkg)
        if run_command(cmd, pkg=pkg, echo=True, stdout=stdout,
                       stderr=stderr) != 0:
            retval = 1

    # Cleanup

    for f in os.listdir(temp_dir):
        os.remove(os.path.join(temp_dir, f))

    # Return to original directory

    os.chdir(call_dir)
    os.rmdir(temp_dir)

    return retval