Python sys.prefix() Examples

The following are 30 code examples for showing how to use sys.prefix(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module sys , or try the search function .

Example 1
Project: cherrypy   Author: cherrypy   File: test_config.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def testUnrepr(self):
        self.getPage('/repr?key=neg')
        self.assertBody('-1234')

        self.getPage('/repr?key=filename')
        self.assertBody(repr(os.path.join(sys.prefix, 'hello.py')))

        self.getPage('/repr?key=thing1')
        self.assertBody(repr(cherrypy.lib.httputil.response_codes[404]))

        if not getattr(cherrypy.server, 'using_apache', False):
            # The object ID's won't match up when using Apache, since the
            # server and client are running in different processes.
            self.getPage('/repr?key=thing2')
            from cherrypy.tutorial import thing2
            self.assertBody(repr(thing2))

        self.getPage('/repr?key=complex')
        self.assertBody('(3+2j)')

        self.getPage('/repr?key=mul')
        self.assertBody('18')

        self.getPage('/repr?key=stradd')
        self.assertBody(repr('112233')) 
Example 2
Project: quart   Author: pgjones   File: helpers.py    License: MIT License 6 votes vote down vote up
def find_package(name: str) -> Tuple[Optional[Path], Path]:
    """Finds packages install prefix (or None) and it's containing Folder
    """
    module = name.split(".")[0]
    loader = pkgutil.get_loader(module)
    if name == "__main__" or loader is None:
        package_path = Path.cwd()
    else:
        if hasattr(loader, "get_filename"):
            filename = loader.get_filename(module)  # type: ignore
        else:
            __import__(name)
            filename = sys.modules[name].__file__
        package_path = Path(filename).resolve().parent
        if hasattr(loader, "is_package"):
            is_package = loader.is_package(module)  # type: ignore
            if is_package:
                package_path = Path(package_path).resolve().parent
    sys_prefix = Path(sys.prefix).resolve()
    try:
        package_path.relative_to(sys_prefix)
    except ValueError:
        return None, package_path
    else:
        return sys_prefix, package_path 
Example 3
Project: razzy-spinner   Author: rafasashi   File: data.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _check_bom(self):
        # Normalize our encoding name
        enc = re.sub('[ -]', '', self.encoding.lower())

        # Look up our encoding in the BOM table.
        bom_info = self._BOM_TABLE.get(enc)

        if bom_info:
            # Read a prefix, to check against the BOM(s)
            bytes = self.stream.read(16)
            self.stream.seek(0)

            # Check for each possible BOM.
            for (bom, new_encoding) in bom_info:
                if bytes.startswith(bom):
                    if new_encoding:
                        self.encoding = new_encoding
                    return len(bom)

        return None 
Example 4
Project: verge3d-blender-addon   Author: Soft8Soft   File: profilehooks.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __str__(self):
        """Return annotated source code for the function."""
        if self.filename is None:
            return "cannot show coverage data since co_filename is None"
        lines = []
        lineno = self.firstlineno
        for line in self.source:
            counter = self.sourcelines.get(lineno)
            if counter is None:
                prefix = ' ' * 7
            elif counter == 0:
                if self.blank_rx.match(line):  # pragma: nocover
                    # This is an workaround for an ancient bug I can't
                    # reproduce, perhaps because it was fixed, or perhaps
                    # because I can't remember all the details.
                    prefix = ' ' * 7
                else:
                    prefix = '>' * 6 + ' '
            else:
                prefix = '%5d: ' % counter
            lines.append(prefix + line)
            lineno += 1
        return ''.join(lines) 
Example 5
Project: linter-pylama   Author: AtomLinter   File: imports.py    License: MIT License 6 votes vote down vote up
def _compute_site_packages():
        def _normalized_path(path):
            return os.path.normcase(os.path.abspath(path))

        paths = set()
        real_prefix = getattr(sys, 'real_prefix', None)
        for prefix in filter(None, (real_prefix, sys.prefix)):
            path = sysconfig.get_python_lib(prefix=prefix)
            path = _normalized_path(path)
            paths.add(path)

        # Handle Debian's derivatives /usr/local.
        if os.path.isfile("/etc/debian_version"):
            for prefix in filter(None, (real_prefix, sys.prefix)):
                libpython = os.path.join(prefix, "local", "lib",
                                         "python" + sysconfig.get_python_version(),
                                         "dist-packages")
                paths.add(libpython)
        return paths 
Example 6
Project: recruit   Author: Frank-qlu   File: system_info.py    License: Apache License 2.0 6 votes vote down vote up
def _find_lib(self, lib_dir, lib, exts):
        assert is_string(lib_dir)
        # under windows first try without 'lib' prefix
        if sys.platform == 'win32':
            lib_prefixes = ['', 'lib']
        else:
            lib_prefixes = ['lib']
        # for each library name, see if we can find a file for it.
        for ext in exts:
            for prefix in lib_prefixes:
                p = self.combine_paths(lib_dir, prefix + lib + ext)
                if p:
                    break
            if p:
                assert len(p) == 1
                # ??? splitext on p[0] would do this for cygwin
                # doesn't seem correct
                if ext == '.dll.a':
                    lib += '.dll'
                if ext == '.lib':
                    lib = prefix + lib
                return lib

        return False 
Example 7
Project: recruit   Author: Frank-qlu   File: mingw32ccompiler.py    License: Apache License 2.0 6 votes vote down vote up
def find_dll(dll_name):

    arch = {'AMD64' : 'amd64',
            'Intel' : 'x86'}[get_build_architecture()]

    def _find_dll_in_winsxs(dll_name):
        # Walk through the WinSxS directory to find the dll.
        winsxs_path = os.path.join(os.environ.get('WINDIR', r'C:\WINDOWS'),
                                   'winsxs')
        if not os.path.exists(winsxs_path):
            return None
        for root, dirs, files in os.walk(winsxs_path):
            if dll_name in files and arch in root:
                return os.path.join(root, dll_name)
        return None

    def _find_dll_in_path(dll_name):
        # First, look in the Python directory, then scan PATH for
        # the given dll name.
        for path in [sys.prefix] + os.environ['PATH'].split(';'):
            filepath = os.path.join(path, dll_name)
            if os.path.exists(filepath):
                return os.path.abspath(filepath)

    return _find_dll_in_winsxs(dll_name) or _find_dll_in_path(dll_name) 
Example 8
Project: recruit   Author: Frank-qlu   File: mingw32ccompiler.py    License: Apache License 2.0 6 votes vote down vote up
def _build_import_library_amd64():
    out_exists, out_file = _check_for_import_lib()
    if out_exists:
        log.debug('Skip building import library: "%s" exists', out_file)
        return

    # get the runtime dll for which we are building import library
    dll_file = find_python_dll()
    log.info('Building import library (arch=AMD64): "%s" (from %s)' %
             (out_file, dll_file))

    # generate symbol list from this library
    def_name = "python%d%d.def" % tuple(sys.version_info[:2])
    def_file = os.path.join(sys.prefix, 'libs', def_name)
    generate_def(dll_file, def_file)

    # generate import library from this symbol list
    cmd = ['dlltool', '-d', def_file, '-l', out_file]
    subprocess.Popen(cmd) 
Example 9
Project: recruit   Author: Frank-qlu   File: util.py    License: Apache License 2.0 6 votes vote down vote up
def get_resources_dests(resources_root, rules):
    """Find destinations for resources files"""

    def get_rel_path(base, path):
        # normalizes and returns a lstripped-/-separated path
        base = base.replace(os.path.sep, '/')
        path = path.replace(os.path.sep, '/')
        assert path.startswith(base)
        return path[len(base):].lstrip('/')


    destinations = {}
    for base, suffix, dest in rules:
        prefix = os.path.join(resources_root, base)
        for abs_base in iglob(prefix):
            abs_glob = os.path.join(abs_base, suffix)
            for abs_path in iglob(abs_glob):
                resource_file = get_rel_path(resources_root, abs_path)
                if dest is None:  # remove the entry if it was here
                    destinations.pop(resource_file, None)
                else:
                    rel_path = get_rel_path(abs_base, abs_path)
                    rel_dest = dest.replace(os.path.sep, '/').rstrip('/')
                    destinations[resource_file] = rel_dest + '/' + rel_path
    return destinations 
Example 10
Project: recruit   Author: Frank-qlu   File: util.py    License: Apache License 2.0 6 votes vote down vote up
def ETA(self):
        if self.done:
            prefix = 'Done'
            t = self.elapsed
            #import pdb; pdb.set_trace()
        else:
            prefix = 'ETA '
            if self.max is None:
                t = -1
            elif self.elapsed == 0 or (self.cur == self.min):
                t = 0
            else:
                #import pdb; pdb.set_trace()
                t = float(self.max - self.min)
                t /= self.cur - self.min
                t = (t - 1) * self.elapsed
        return '%s: %s' % (prefix, self.format_duration(t)) 
Example 11
Project: recruit   Author: Frank-qlu   File: outdated.py    License: Apache License 2.0 6 votes vote down vote up
def save(self, pypi_version, current_time):
        # Check to make sure that we own the directory
        if not check_path_owner(os.path.dirname(self.statefile_path)):
            return

        # Now that we've ensured the directory is owned by this user, we'll go
        # ahead and make sure that all our directories are created.
        ensure_dir(os.path.dirname(self.statefile_path))

        # Attempt to write out our version check file
        with lockfile.LockFile(self.statefile_path):
            if os.path.exists(self.statefile_path):
                with open(self.statefile_path) as statefile:
                    state = json.load(statefile)
            else:
                state = {}

            state[sys.prefix] = {
                "last_check": current_time.strftime(SELFCHECK_DATE_FMT),
                "pypi_version": pypi_version,
            }

            with open(self.statefile_path, "w") as statefile:
                json.dump(state, statefile, sort_keys=True,
                          separators=(",", ":")) 
Example 12
Project: jbox   Author: jpush   File: util.py    License: MIT License 6 votes vote down vote up
def get_resources_dests(resources_root, rules):
    """Find destinations for resources files"""

    def get_rel_path(base, path):
        # normalizes and returns a lstripped-/-separated path
        base = base.replace(os.path.sep, '/')
        path = path.replace(os.path.sep, '/')
        assert path.startswith(base)
        return path[len(base):].lstrip('/')


    destinations = {}
    for base, suffix, dest in rules:
        prefix = os.path.join(resources_root, base)
        for abs_base in iglob(prefix):
            abs_glob = os.path.join(abs_base, suffix)
            for abs_path in iglob(abs_glob):
                resource_file = get_rel_path(resources_root, abs_path)
                if dest is None:  # remove the entry if it was here
                    destinations.pop(resource_file, None)
                else:
                    rel_path = get_rel_path(abs_base, abs_path)
                    rel_dest = dest.replace(os.path.sep, '/').rstrip('/')
                    destinations[resource_file] = rel_dest + '/' + rel_path
    return destinations 
Example 13
Project: jbox   Author: jpush   File: util.py    License: MIT License 6 votes vote down vote up
def write_exports(exports, stream):
    if sys.version_info[0] >= 3:
        # needs to be a text stream
        stream = codecs.getwriter('utf-8')(stream)
    cp = configparser.ConfigParser()
    for k, v in exports.items():
        # TODO check k, v for valid values
        cp.add_section(k)
        for entry in v.values():
            if entry.suffix is None:
                s = entry.prefix
            else:
                s = '%s:%s' % (entry.prefix, entry.suffix)
            if entry.flags:
                s = '%s [%s]' % (s, ', '.join(entry.flags))
            cp.set(k, entry.name, s)
    cp.write(stream) 
Example 14
Project: jbox   Author: jpush   File: util.py    License: MIT License 6 votes vote down vote up
def ETA(self):
        if self.done:
            prefix = 'Done'
            t = self.elapsed
            #import pdb; pdb.set_trace()
        else:
            prefix = 'ETA '
            if self.max is None:
                t = -1
            elif self.elapsed == 0 or (self.cur == self.min):
                t = 0
            else:
                #import pdb; pdb.set_trace()
                t = float(self.max - self.min)
                t /= self.cur - self.min
                t = (t - 1) * self.elapsed
        return '%s: %s' % (prefix, self.format_duration(t)) 
Example 15
Project: jbox   Author: jpush   File: outdated.py    License: MIT License 6 votes vote down vote up
def save(self, pypi_version, current_time):
        # Check to make sure that we own the directory
        if not check_path_owner(os.path.dirname(self.statefile_path)):
            return

        # Now that we've ensured the directory is owned by this user, we'll go
        # ahead and make sure that all our directories are created.
        ensure_dir(os.path.dirname(self.statefile_path))

        # Attempt to write out our version check file
        with lockfile.LockFile(self.statefile_path):
            if os.path.exists(self.statefile_path):
                with open(self.statefile_path) as statefile:
                    state = json.load(statefile)
            else:
                state = {}

            state[sys.prefix] = {
                "last_check": current_time.strftime(SELFCHECK_DATE_FMT),
                "pypi_version": pypi_version,
            }

            with open(self.statefile_path, "w") as statefile:
                json.dump(state, statefile, sort_keys=True,
                          separators=(",", ":")) 
Example 16
Project: jbox   Author: jpush   File: easy_install.py    License: MIT License 6 votes vote down vote up
def run(self):
        if self.verbose != self.distribution.verbose:
            log.set_verbosity(self.verbose)
        try:
            for spec in self.args:
                self.easy_install(spec, not self.no_deps)
            if self.record:
                outputs = self.outputs
                if self.root:  # strip any package prefix
                    root_len = len(self.root)
                    for counter in range(len(outputs)):
                        outputs[counter] = outputs[counter][root_len:]
                from distutils import file_util

                self.execute(
                    file_util.write_file, (self.record, outputs),
                    "writing list of installed files to '%s'" %
                    self.record
                )
            self.warn_deprecated_options()
        finally:
            log.set_verbosity(self.distribution.verbose) 
Example 17
Project: jbox   Author: jpush   File: easy_install.py    License: MIT License 6 votes vote down vote up
def build_and_install(self, setup_script, setup_base):
        args = ['bdist_egg', '--dist-dir']

        dist_dir = tempfile.mkdtemp(
            prefix='egg-dist-tmp-', dir=os.path.dirname(setup_script)
        )
        try:
            self._set_fetcher_options(os.path.dirname(setup_script))
            args.append(dist_dir)

            self.run_setup(setup_script, setup_base, args)
            all_eggs = Environment([dist_dir])
            eggs = []
            for key in all_eggs:
                for dist in all_eggs[key]:
                    eggs.append(self.install_egg(dist.location, setup_base))
            if not eggs and not self.dry_run:
                log.warn("No eggs found in %s (setup script problem?)",
                         dist_dir)
            return eggs
        finally:
            rmtree(dist_dir)
            log.set_verbosity(self.verbose)  # restore our log verbosity 
Example 18
Project: jbox   Author: jpush   File: easy_install.py    License: MIT License 6 votes vote down vote up
def _expand(self, *attrs):
        config_vars = self.get_finalized_command('install').config_vars

        if self.prefix:
            # Set default install_dir/scripts from --prefix
            config_vars = config_vars.copy()
            config_vars['base'] = self.prefix
            scheme = self.INSTALL_SCHEMES.get(os.name, self.DEFAULT_SCHEME)
            for attr, val in scheme.items():
                if getattr(self, attr, None) is None:
                    setattr(self, attr, val)

        from distutils.util import subst_vars

        for attr in attrs:
            val = getattr(self, attr)
            if val is not None:
                val = subst_vars(val, config_vars)
                if os.name == 'posix':
                    val = os.path.expanduser(val)
                setattr(self, attr, val) 
Example 19
Project: jbox   Author: jpush   File: paths.py    License: MIT License 6 votes vote down vote up
def get_install_paths(name):
    """
    Return the (distutils) install paths for the named dist.
    
    A dict with ('purelib', 'platlib', 'headers', 'scripts', 'data') keys.
    """
    paths = {}

    i = get_install_command(name)

    for key in install.SCHEME_KEYS:
        paths[key] = getattr(i, 'install_' + key)

    # pip uses a similar path as an alternative to the system's (read-only)
    # include directory:
    if hasattr(sys, 'real_prefix'):  # virtualenv
        paths['headers'] = os.path.join(sys.prefix,
                                        'include',
                                        'site',
                                        'python' + sys.version[:3],
                                        name)

    return paths 
Example 20
Project: mishkal   Author: linuxscout   File: cache.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, cache_path=False):
        """
        Create Analex Cache
        """
        # use this dictionary as a local cache,
        # The global db will be updated on destructing object
        # get the database path
        if hasattr(sys, 'frozen'): # only when running in py2exe this exists
            base = sys.prefix
        else: # otherwise this is a regular python script
            base = os.path.dirname(os.path.realpath(__file__))
        if not cache_path:
            file_path = self.DB_PATH
        else:
            file_path = os.path.join(os.path.dirname(cache_path), '.thaalabCache')
        
        self.cache={};
        self.db = Database(file_path)
        if not self.db.exists():
            self.db.create();
            x_ind = WithAIndex(self.db.path, 'a')
            self.db.add_index(x_ind)        
        else:
            self.db.open(); 
Example 21
Project: mealpy   Author: edmundmok   File: venv_update.py    License: MIT License 5 votes vote down vote up
def exec_scratch_virtualenv(args):
    """
    goals:
        - get any random site-packages off of the pythonpath
        - ensure we can import virtualenv
        - ensure that we're not using the interpreter that we may need to delete
        - idempotency: do nothing if the above goals are already met
    """
    scratch = Scratch()
    if not exists(scratch.python):
        run(('virtualenv', scratch.venv))

    if not exists(join(scratch.src, 'virtualenv.py')):
        scratch_python = venv_python(scratch.venv)
        # TODO: do we allow user-defined override of which version of virtualenv to install?
        tmp = scratch.src + '.tmp'
        run((scratch_python, '-m', 'pip.__main__', 'install', 'virtualenv', '--target', tmp))

        from os import rename
        rename(tmp, scratch.src)

    import sys
    from os.path import realpath
    # We want to compare the paths themselves as sometimes sys.path is the same
    # as scratch.venv, but with a suffix of bin/..
    if realpath(sys.prefix) != realpath(scratch.venv):
        # TODO-TEST: sometimes we would get a stale version of venv-update
        exec_((scratch.python, dotpy(__file__)) + args)  # never returns

    # TODO-TEST: the original venv-update's directory was on sys.path (when using symlinking)
    sys.path[0] = scratch.src 
Example 22
Project: misp42splunk   Author: remg427   File: __init__.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def setup_detect_python2():
        """
        Call this before using the refactoring tools to create them on demand
        if needed.
        """
        if None in [RTs._rt_py2_detect, RTs._rtp_py2_detect]:
            RTs._rt_py2_detect = RefactoringTool(py2_detect_fixers)
            RTs._rtp_py2_detect = RefactoringTool(py2_detect_fixers,
                                                  {'print_function': True})


# We need to find a prefix for the standard library, as we don't want to
# process any files there (they will already be Python 3).
#
# The following method is used by Sanjay Vinip in uprefix. This fails for
# ``conda`` environments:
#     # In a non-pythonv virtualenv, sys.real_prefix points to the installed Python.
#     # In a pythonv venv, sys.base_prefix points to the installed Python.
#     # Outside a virtual environment, sys.prefix points to the installed Python.

#     if hasattr(sys, 'real_prefix'):
#         _syslibprefix = sys.real_prefix
#     else:
#         _syslibprefix = getattr(sys, 'base_prefix', sys.prefix)

# Instead, we use the portion of the path common to both the stdlib modules
# ``math`` and ``urllib``. 
Example 23
Project: misp42splunk   Author: remg427   File: __init__.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def setup_detect_python2():
        """
        Call this before using the refactoring tools to create them on demand
        if needed.
        """
        if None in [RTs._rt_py2_detect, RTs._rtp_py2_detect]:
            RTs._rt_py2_detect = RefactoringTool(py2_detect_fixers)
            RTs._rtp_py2_detect = RefactoringTool(py2_detect_fixers,
                                                  {'print_function': True})


# We need to find a prefix for the standard library, as we don't want to
# process any files there (they will already be Python 3).
#
# The following method is used by Sanjay Vinip in uprefix. This fails for
# ``conda`` environments:
#     # In a non-pythonv virtualenv, sys.real_prefix points to the installed Python.
#     # In a pythonv venv, sys.base_prefix points to the installed Python.
#     # Outside a virtual environment, sys.prefix points to the installed Python.

#     if hasattr(sys, 'real_prefix'):
#         _syslibprefix = sys.real_prefix
#     else:
#         _syslibprefix = getattr(sys, 'base_prefix', sys.prefix)

# Instead, we use the portion of the path common to both the stdlib modules
# ``math`` and ``urllib``. 
Example 24
Project: linter-pylama   Author: AtomLinter   File: modutils.py    License: MIT License 5 votes vote down vote up
def _posix_path(path):
        base_python = 'python%d.%d' % sys.version_info[:2]
        return os.path.join(prefix, path, base_python) 
Example 25
Project: linter-pylama   Author: AtomLinter   File: imports.py    License: MIT License 5 votes vote down vote up
def _make_tree_defs(mod_files_list):
    """get a list of 2-uple (module, list_of_files_which_import_this_module),
    it will return a dictionary to represent this as a tree
    """
    tree_defs = {}
    for mod, files in mod_files_list:
        node = (tree_defs, ())
        for prefix in mod.split('.'):
            node = node[0].setdefault(prefix, [{}, []])
        node[1] += files
    return tree_defs 
Example 26
Project: tributary   Author: timkpaine   File: conf.py    License: Apache License 2.0 5 votes vote down vote up
def run_apidoc(_):
    out_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'api'))
    lib_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'tributary'))
    cmd_path = 'sphinx-apidoc'
    if hasattr(sys, 'real_prefix'):  # Check to see if we are in a virtualenv
        # If we are, assemble the path manually
        cmd_path = os.path.abspath(os.path.join(sys.prefix, 'bin', 'sphinx-apidoc'))
    subprocess.check_call([cmd_path,
                           '-E',
                           '-M',
                           '-o',
                           out_dir,
                           lib_dir,
                           '--force']) 
Example 27
Project: recruit   Author: Frank-qlu   File: system_info.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self):
        include_dirs = []
        try:
            module = __import__(self.modulename)
            prefix = []
            for name in module.__file__.split(os.sep):
                if name == 'lib':
                    break
                prefix.append(name)

            # Ask numpy for its own include path before attempting
            # anything else
            try:
                include_dirs.append(getattr(module, 'get_include')())
            except AttributeError:
                pass

            include_dirs.append(distutils.sysconfig.get_python_inc(
                                        prefix=os.sep.join(prefix)))
        except ImportError:
            pass
        py_incl_dir = distutils.sysconfig.get_python_inc()
        include_dirs.append(py_incl_dir)
        py_pincl_dir = distutils.sysconfig.get_python_inc(plat_specific=True)
        if py_pincl_dir not in include_dirs:
            include_dirs.append(py_pincl_dir)
        for d in default_include_dirs:
            d = os.path.join(d, os.path.basename(py_incl_dir))
            if d not in include_dirs:
                include_dirs.append(d)
        system_info.__init__(self,
                             default_lib_dirs=[],
                             default_include_dirs=include_dirs) 
Example 28
Project: recruit   Author: Frank-qlu   File: mingw32ccompiler.py    License: Apache License 2.0 5 votes vote down vote up
def find_python_dll():
    # We can't do much here:
    # - find it in the virtualenv (sys.prefix)
    # - find it in python main dir (sys.base_prefix, if in a virtualenv)
    # - sys.real_prefix is main dir for virtualenvs in Python 2.7
    # - in system32,
    # - ortherwise (Sxs), I don't know how to get it.
    stems = [sys.prefix]
    if hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix:
        stems.append(sys.base_prefix)
    elif hasattr(sys, 'real_prefix') and sys.real_prefix != sys.prefix:
        stems.append(sys.real_prefix)

    sub_dirs = ['', 'lib', 'bin']
    # generate possible combinations of directory trees and sub-directories
    lib_dirs = []
    for stem in stems:
        for folder in sub_dirs:
            lib_dirs.append(os.path.join(stem, folder))

    # add system directory as well
    if 'SYSTEMROOT' in os.environ:
        lib_dirs.append(os.path.join(os.environ['SYSTEMROOT'], 'System32'))

    # search in the file system for possible candidates
    major_version, minor_version = tuple(sys.version_info[:2])
    patterns = ['python%d%d.dll']

    for pat in patterns:
        dllname = pat % (major_version, minor_version)
        print("Looking for %s" % dllname)
        for folder in lib_dirs:
            dll = os.path.join(folder, dllname)
            if os.path.exists(dll):
                return dll

    raise ValueError("%s not found in %s" % (dllname, lib_dirs)) 
Example 29
Project: recruit   Author: Frank-qlu   File: setup.py    License: Apache License 2.0 5 votes vote down vote up
def pythonlib_dir():
    """return path where libpython* is."""
    if sys.platform == 'win32':
        return os.path.join(sys.prefix, "libs")
    else:
        return get_config_var('LIBDIR') 
Example 30
Project: recruit   Author: Frank-qlu   File: util.py    License: Apache License 2.0 5 votes vote down vote up
def in_venv():
    if hasattr(sys, 'real_prefix'):
        # virtualenv venvs
        result = True
    else:
        # PEP 405 venvs
        result = sys.prefix != getattr(sys, 'base_prefix', sys.prefix)
    return result