⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 __init__.py

📁 利用C
💻 PY
📖 第 1 页 / 共 3 页
字号:
        for f in dataHash["pythonModules"]:            dpath = os.path.dirname(f.abspath)            if dpath not in pyPath:                pyPath.append(dpath)        environ = os.environ.copy()        environ["LD_LIBRARY_PATH"] = os.pathsep.join(ldPath + environ.get("LD_LIBRARY_PATH", "").split(os.pathsep))        environ["PYTHONPATH"] = os.pathsep.join(pyPath + environ.get("PYTHONPATH", "").split(os.pathsep))        oldDir = os.getcwd()        os.chdir("tests")        try:            r = os.spawnlpe(os.P_WAIT, "python", "python", "runtests.py", environ)        finally:            os.chdir(oldDir)        return r    return _runTestsdef _strRuntests(target, source, env):    return "Running tests"def qualifiedPathName(path):    """Returns False if path contains a directory starting with dot. Else True"""    for component in path.split(os.path.sep):        if component[0] == ".": # omitt if a directory starts with .              return False    return Trueexclude_suffixes = (".pyc",".pyo",".tmp")def qualifiedFileName(filename):    """Returns False if filename starts with dot, or has illegal suffix.    Illegal suffixes are defined in the exclude_suffixes module list.    """    if filename[0] == "." or os.path.splitext(filename)[1] in exclude_suffixes:         return False    return Truedef globFiles(dir, pattern,returnFile=True):    from glob import glob    if returnFile:        return [_defaultEnv.File(f) for f in glob(os.path.join(dir, pattern))]    else:        return glob(os.path.join(dir, pattern))#--------------------------------------------------------------------# Figure out if and how to edit common.py# Edit common.py# Add installer for common.py to the environment#--------------------------------------------------------------------def installCommonFile(env, commonfile, prefix):    if os.path.isfile(commonfile):        RelativeDataDir = os.path.join("share", "pycc", "data")        # Determine path to data from pycc.common module        pyccPyPath = os.path.normpath(os.path.join(env.subst(env["pythonModuleDir"]), "pycc"))        # Find out how to get from the pythonModuleDir to the data dir:        commonprefix = os.path.commonprefix((prefix,pyccPyPath))        prefixdiff = prefix[len(commonprefix):]        RelativeDataDir = os.path.join(prefixdiff,RelativeDataDir)        pyccPyPathRel = pyccPyPath[len(commonprefix):]        _dataLevelsBeneath = len(pyccPyPathRel.split(os.path.sep))        # create a callback for editing of common.py, in order to have        # correct location of DataDir:        callback = setConstants(_dataLevelsBeneath, RelativeDataDir)        env.Alias("install",                 env.Command(os.path.join("$pythonModuleDir", "pycc", "common.py"),                     commonfile, callback))    return envdef buildFileList(dirs,glob="*.py",exclude=[]):    """Build a list of python files to be installed in site-packages.       Preserve the directory structure.    """    installfiles = []    for p in dirs:        for dpath, dnames, fnames in os.walk(p.path):            srcPath = dpath.split(os.path.sep,1)[0]            pyPath = os.path.sep.join(dpath.split(os.path.sep,1)[1:])            if not qualifiedPathName(dpath): continue            installfiles += globFiles(dpath,glob,returnFile=False)    for excl in exclude:        try: del(installfiles[installfiles.index(excl)])        except: pass    return installfilesdef addInstallTargets(env, sourcefiles=[], targetdir=""):    """Add install targets to env from a list of files"""    for f in sourcefiles:        env.InstallAs(os.path.join(targetdir, f.path.split(os.path.sep, 1)[1]), f)    env.Alias("install",targetdir)    return envdef intlist(l):    """Convert a list of strings to ints if possible. Leave the string     if not possible to convert.    """    return_l = []    for item in l:        try: item = int(item)        except: pass        return_l.append(item)    return return_ldef checkVersion(v_check, v_required):    """ Check that v_check is bigger that v_required """        delimiters = re.compile(r"[._-]")    vc = re.split(delimiters, v_check)    vr = re.split(delimiters, v_required)    vc = intlist(vc)    vr = intlist(vr)    length = min(len(vr), len(vc))    for i in xrange(length):        if vc[i] > vr[i]:            return True        elif vc[i] < vr[i]:            return False    # If the required version is the longest and we reach this place:    # E.g.: checkVersion("1.2.15", "1.2.15.1") -> False    if len(vr)-len(vc) > 0:        return False    # Identical versions, return True    return True# Find modules ( srcnode must be updated ) def getModules(configuredPackages, resolve_deps=True, directory="."):    """Generate module objects from specification files in module directories. Directories starting with a dot,       e.g. ".ShadowModule" will not be processed              @param A dictionary of packages that is already configured       @param A flag indicating whether dependencies should be resolved; if True,               modules with dependencies not present in configuredPackages will be               removed from the list       @return A dictionary of L{module<_Module>} objects.    """    modules = {}    srcDir = _defaultEnv.Dir(directory).srcnode().abspath    if not srcDir[-1] == os.path.sep:        srcDir += os.path.sep    for dpath, dnames, fnames in os.walk(srcDir):        dpath = dpath[len(srcDir):] # Make relative to source dir        for d in dnames[:]:            if d.startswith("."):                # Ignore dirs starting with '.'                dnames.remove(d)                continue            mpath = os.path.join(dpath, d)            try: mod = readModuleConfig(os.path.join(srcDir, mpath), mpath, _defaultEnv)            except NoModule:                # No module configuration                continue            modules[mod.name] = mod    # if no module found, try in given "directory":    # Maybe we should do this always?    # Finally, check for config file (scons.cfg) in the root of the project:    try:       mod = readModuleConfig(srcDir, ".", _defaultEnv)      modules[mod.name] = mod    except NoModule:      pass            if resolve_deps:        modules = resolveModuleDependencies(modules, configuredPackages)    return modulesdef getModulesAndDependencies(directory=".",                              configuredPackages={}, disabled_packages=[]):    """Find all modules and dependencies in the project.    @return tuple with modules, external dependenices for each module, both             dicts, a hash with all dependencies listed, and a hash with the            PkgConfig objects that are created.    """    # Find all modules:    modules = getModules({}, resolve_deps=False, directory=directory)    # next, build a list of all external dependencies for each module.    # We also include the optional dependencies, as those are separated    # inside the module anyway.    dependencies = {}    packcfgObjs = {}    # all dependencies accumulated in one hash (will be returned as a list, but    # it is simpler to build a uniq list in a hash, using .has_key)    alldependencies = {}    for module_name, module in modules.items():        dependencies[module_name] = {}        dict_deps = {}        seq_deps = []        # Dependencies - both mandatory and optional.        if isinstance(module.dependencies, dict):            dict_deps.update(module.dependencies)        else:            seq_deps += module.dependencies        if isinstance(module.optDependencies, dict):            dict_deps.update(module.optDependencies)        else:            seq_deps += module.optDependencies         if isinstance(module.swigDependencies, dict):          dict_deps.update(module.swigDependencies)        else:          seq_deps += module.swigDependencies        # Handle dependencies with a version requirement.        for package,version in dict_deps.items():            if not modules.has_key(package):                # this is an external dependency                if not dependencies[module_name].has_key(package):                    dependencies[module_name][package] = version                else:                    # Dependency already registered. We update the information                     # either if the previous registration was with None as                     # version or an older version was requested earlier.                    if not dependencies[module_name][package]:                        dependencies[module_name][package] = version                    elif checkVersion(version,dependencies[module_name][package]):                        dependencies[module_name][package] = version                # We also make sure that the package is present in                 # alldependencies with the correct version info                if not alldependencies.has_key(package):                    # not present, add                    alldependencies[package] = version                else:                    # already present, update version if necessary:                    alldependencies[package] = dependencies[module_name][package]        # Handle dependencies without any version requested.        for package in seq_deps:            if not modules.has_key(package):                # this is an external dependency                # Add in the dependencies with None as version if not previously                 # listed                if not dependencies[module_name].has_key(package):                    dependencies[module_name][package] = None                # Also, add in alldependencies if not already present:                if not alldependencies.has_key(package):                    alldependencies[package] = None    # See which packages that can be resolved with PkgConfig right away    # We can get a configuredPackages dict as input. If so, check that     # the package is not already there.    for d in alldependencies.keys():         if configuredPackages.has_key(d):          continue        if d in disabled_packages:          # skip this dependency since it should be disabled          continue        print "Checking for %s..." % (d),        try:          packcfg = pkgconfig.PkgConfig(d, env=_defaultEnv)          configuredPackages[d] = Customize.Dependency(cppPath=packcfg.includeDirs(), \                                    libPath=packcfg.libDirs(),\                                    libs=packcfg.libs(),\                                    linkOpts=packcfg.linkOpts(),\                                    version=packcfg.version(),\                                    compiler=packcfg.compiler())          packcfgObjs[d] = packcfg        except:          print "failed"##           print "failed"##           print """ *** Unable to generate a suitable pkg-config file for %s.##  *** If %s is present on your system, try setting the %s_DIR ##  *** environment variable to the directory where %s is installed.""" % (d,d,str.upper(d),d)##           if os.environ.has_key("%s_DIR" % (str.upper(d))):##             print " *** %s_DIR is currently set to %s" % (str.upper(d),os.environ["%s_DIR" % (str.upper(d))])    return modules,dependencies,alldependencies,configuredPackages,packcfgObjsdef addToDependencies(deps,pack,ver=None):    # Add new package into existing dependencies    if isinstance(deps, dict):        # original deps is a dict, with versions        if deps.has_key(pack):            # update if previously registered with None             if not deps[pack]:                deps[pack] = ver            # or if previously registered with older version            elif checkVersion(ver,deps[pack]):                deps[pack] = ver        else:            deps[pack] = ver    else:        # original deps is just a list, we append the new pack        # if not already present.         # We don't care about version, that should be resolved before         # we add the new package.        if pack not in deps:            deps += [pack]def resolveCompiler(configuredPackages, packcfgObjs, sconsEnv):  """Find a common compiler for this package and it's external dependencies           We have to make sure that this package and its dependencies can be compiled     using a common compiler. An example is that PETSc may request mpicc if     it was compiled with that one, while g++ is the default option for the     current package. In that case, mpic++ or mpicxx should probably be used.      The pkg-config generators for external modules should provide a pkgTests      method that takes optionally a compiler, if the compiler is an important     issue for the package. We call on this method to run tests with a      specific compiler     pkg-config files for packages that needs a specific compiler should      include the compiler variable. The pkg-config opbject in the      configuredPackages hash will hold this compiler in the compiler      variable. The variable is None if none compiler is requested.   """   # TODO: I should probably also handle linker here. Maybe we should assume   # compiler is a tuple with (compiler,linker) and if it is just a string,   # change it into (compiler,compiler) (i.e. assume that compiler and linker  # is the same.  # Or we can handle this in the pkgconfig generator, which is how it is done   # right now...  print "Resolving compiler...",  verifiedPackages = {}  compiler = sconsEnv["CXX"]  for pack, dep in configuredPackages.items():    # If both compiler and dep.compiler is set:    if dep.compiler and compiler:      # if dep.compiler and compiler differ, we must do a full check.      if dep.compiler != compiler:        try:          dep_packgen = pkgconfig.get_packgen(pack)        except PkgconfigGeneratorMissing:          log2("No pkg-config generator for package '%s'. Assuming Ok." % pack)          verifiedPackages[pack] = dep          continue        # case 1: Try the new package with the old compiler        # If ok, mark the new package as verified        flag = True        try:          dep_packcfg = packcfgObjs[pack]          dep_packgen.pkgTests(forceCompiler=compiler, sconsEnv=sconsEnv,                               cflags=dep_packcfg.cflags(), libs=dep_packcfg.ldflags())        except Exception, msg:          log2("Some tests failed for package '%s'. Discarding package." % pack)          log2(msg)          flag = False        if flag:          verifiedPackages[pack] = dep

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -