Python sys.prefix() Examples

The following are code examples for showing how to use sys.prefix(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: python-   Author: secondtonone1   File: util.py    (license) View Source Project 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 2
Project: python-   Author: secondtonone1   File: util.py    (license) View Source Project 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 3
Project: python-   Author: secondtonone1   File: util.py    (license) View Source Project 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 4
Project: python-   Author: secondtonone1   File: outdated.py    (license) View Source Project 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 5
Project: python-   Author: secondtonone1   File: paths.py    (license) View Source Project 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 6
Project: python-   Author: secondtonone1   File: easy_install.py    (license) View Source Project 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 7
Project: python-   Author: secondtonone1   File: easy_install.py    (license) View Source Project 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 8
Project: python-   Author: secondtonone1   File: easy_install.py    (license) View Source Project 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 9
Project: python-   Author: secondtonone1   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def find_config_files(self):
    found = old_find_config_files(self)
    system_distutils = os.path.join(distutils_path, 'distutils.cfg')
    #if os.path.exists(system_distutils):
    #    found.insert(0, system_distutils)
        # What to call the per-user config file
    if os.name == 'posix':
        user_filename = ".pydistutils.cfg"
    else:
        user_filename = "pydistutils.cfg"
    user_filename = os.path.join(sys.prefix, user_filename)
    if os.path.isfile(user_filename):
        for item in list(found):
            if item.endswith('pydistutils.cfg'):
                found.remove(item)
        found.append(user_filename)
    return found 
Example 10
Project: cookiecutter-django-app   Author: edx   File: conf.py    (GNU Affero General Public License v3.0) View Source Project 6 votes vote down vote up
def on_init(app):  # pylint: disable=unused-argument
    """
    Run sphinx-apidoc after Sphinx initialization.

    Read the Docs won't run tox or custom shell commands, so we need this to
    avoid checking in the generated reStructuredText files.
    """
    docs_path = os.path.abspath(os.path.dirname(__file__))
    root_path = os.path.abspath(os.path.join(docs_path, '..'))
    apidoc_path = 'sphinx-apidoc'
    if hasattr(sys, 'real_prefix'):  # Check to see if we are in a virtualenv
        # If we are, assemble the path manually
        bin_path = os.path.abspath(os.path.join(sys.prefix, 'bin'))
        apidoc_path = os.path.join(bin_path, apidoc_path)
    check_call([apidoc_path, '-o', docs_path, os.path.join(root_path, '{{ cookiecutter.app_name }}'),
                os.path.join(root_path, '{{ cookiecutter.app_name }}/migrations')]) 
Example 11
Project: my-first-blog   Author: AnkurBegining   File: util.py    (license) View Source Project 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 12
Project: my-first-blog   Author: AnkurBegining   File: util.py    (license) View Source Project 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 13
Project: my-first-blog   Author: AnkurBegining   File: util.py    (license) View Source Project 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 14
Project: my-first-blog   Author: AnkurBegining   File: outdated.py    (license) View Source Project 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 15
Project: my-first-blog   Author: AnkurBegining   File: paths.py    (license) View Source Project 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 16
Project: my-first-blog   Author: AnkurBegining   File: easy_install.py    (license) View Source Project 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: my-first-blog   Author: AnkurBegining   File: easy_install.py    (license) View Source Project 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: my-first-blog   Author: AnkurBegining   File: easy_install.py    (license) View Source Project 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: my-first-blog   Author: AnkurBegining   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def find_config_files(self):
    found = old_find_config_files(self)
    system_distutils = os.path.join(distutils_path, 'distutils.cfg')
    #if os.path.exists(system_distutils):
    #    found.insert(0, system_distutils)
        # What to call the per-user config file
    if os.name == 'posix':
        user_filename = ".pydistutils.cfg"
    else:
        user_filename = "pydistutils.cfg"
    user_filename = os.path.join(sys.prefix, user_filename)
    if os.path.isfile(user_filename):
        for item in list(found):
            if item.endswith('pydistutils.cfg'):
                found.remove(item)
        found.append(user_filename)
    return found 
Example 20
Project: kinect-2-libras   Author: inessadl   File: install.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def finalize_other (self):          # Windows and Mac OS for now

        if self.user:
            if self.install_userbase is None:
                raise DistutilsPlatformError(
                    "User base directory is not specified")
            self.install_base = self.install_platbase = self.install_userbase
            self.select_scheme(os.name + "_user")
        elif self.home is not None:
            self.install_base = self.install_platbase = self.home
            self.select_scheme("unix_home")
        else:
            if self.prefix is None:
                self.prefix = os.path.normpath(sys.prefix)

            self.install_base = self.install_platbase = self.prefix
            try:
                self.select_scheme(os.name)
            except KeyError:
                raise DistutilsPlatformError, \
                      "I don't know how to install stuff on '%s'" % os.name

    # finalize_other () 
Example 21
Project: anonymine   Author: oskar-skog   File: configure.py    (license) View Source Project 6 votes vote down vote up
def find_EXECUTABLES(Makefile, flags):
    '''
    See the doc-string for find_prefix as well.
    
    Set Makefile['EXECUTABLES'] if needed to.
    Depends (directly) on $(gamesdir) and $(bindir).
    Depends (indirectly) on $(prefix).
    '''
    if 'EXECUTABLES' not in Makefile:
        acceptable = os.getenv('PATH').split(':')
        for exec_dir in ('gamesdir', 'bindir'):
            if expand(exec_dir, Makefile) in acceptable:
                Makefile['EXECUTABLES'] = '$('+exec_dir+')'
                return False
        else:
            return True
    else:
        return False 
Example 22
Project: anonymine   Author: oskar-skog   File: configure.py    (license) View Source Project 6 votes vote down vote up
def find_sysconfdir(Makefile, flags):
    '''
    See the doc-string for find_prefix as well.
    
    Set Makefile['sysconfdir'] if needed to.
    Depends on $(prefix)
    '''
    if 'sysconfdir' in Makefile:
        return False
    else:
        try:
            os.listdir(expand('prefix', Makefile) + '/etc')
            Makefile['sysconfdir'] = '$(prefix)/etc'
            return False
        except:
            pass
        Makefile['sysconfdir'] = '/etc'
        return False 
Example 23
Project: Flask_Blog   Author: sugarguo   File: util.py    (GNU General Public License v3.0) View Source Project 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 24
Project: Flask_Blog   Author: sugarguo   File: util.py    (GNU General Public License v3.0) View Source Project 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 25
Project: Flask_Blog   Author: sugarguo   File: util.py    (GNU General Public License v3.0) View Source Project 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 26
Project: Flask_Blog   Author: sugarguo   File: config.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def test_installed_module_paths(self):
        here = os.path.abspath(os.path.dirname(__file__))
        expected_prefix = os.path.join(here, 'test_apps')
        real_prefix, sys.prefix = sys.prefix, expected_prefix
        site_packages = os.path.join(expected_prefix, 'lib', 'python2.5', 'site-packages')
        sys.path.append(site_packages)
        try:
            import site_app
            self.assert_equal(site_app.app.instance_path,
                              os.path.join(expected_prefix, 'var',
                                           'site_app-instance'))
        finally:
            sys.prefix = real_prefix
            sys.path.remove(site_packages)
            if 'site_app' in sys.modules:
                del sys.modules['site_app'] 
Example 27
Project: Flask_Blog   Author: sugarguo   File: config.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def test_installed_module_paths_with_limited_loader(self):
        here = os.path.abspath(os.path.dirname(__file__))
        expected_prefix = os.path.join(here, 'test_apps')
        real_prefix, sys.prefix = sys.prefix, expected_prefix
        site_packages = os.path.join(expected_prefix, 'lib', 'python2.5', 'site-packages')
        sys.path.append(site_packages)
        with patch_pkgutil_get_loader():
            try:
                import site_app
                self.assert_equal(site_app.app.instance_path,
                                  os.path.join(expected_prefix, 'var',
                                               'site_app-instance'))
            finally:
                sys.prefix = real_prefix
                sys.path.remove(site_packages)
                if 'site_app' in sys.modules:
                    del sys.modules['site_app'] 
Example 28
Project: Flask_Blog   Author: sugarguo   File: config.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def test_installed_package_paths(self):
        here = os.path.abspath(os.path.dirname(__file__))
        expected_prefix = os.path.join(here, 'test_apps')
        real_prefix, sys.prefix = sys.prefix, expected_prefix
        installed_path = os.path.join(expected_prefix, 'path')
        sys.path.append(installed_path)
        try:
            import installed_package
            self.assert_equal(installed_package.app.instance_path,
                              os.path.join(expected_prefix, 'var',
                                           'installed_package-instance'))
        finally:
            sys.prefix = real_prefix
            sys.path.remove(installed_path)
            if 'installed_package' in sys.modules:
                del sys.modules['installed_package'] 
Example 29
Project: Flask_Blog   Author: sugarguo   File: config.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def test_prefix_package_paths(self):
        here = os.path.abspath(os.path.dirname(__file__))
        expected_prefix = os.path.join(here, 'test_apps')
        real_prefix, sys.prefix = sys.prefix, expected_prefix
        site_packages = os.path.join(expected_prefix, 'lib', 'python2.5', 'site-packages')
        sys.path.append(site_packages)
        try:
            import site_package
            self.assert_equal(site_package.app.instance_path,
                              os.path.join(expected_prefix, 'var',
                                           'site_package-instance'))
        finally:
            sys.prefix = real_prefix
            sys.path.remove(site_packages)
            if 'site_package' in sys.modules:
                del sys.modules['site_package'] 
Example 30
Project: Flask_Blog   Author: sugarguo   File: config.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def test_prefix_package_paths_with_limited_loader(self):
        here = os.path.abspath(os.path.dirname(__file__))
        expected_prefix = os.path.join(here, 'test_apps')
        real_prefix, sys.prefix = sys.prefix, expected_prefix
        site_packages = os.path.join(expected_prefix, 'lib', 'python2.5', 'site-packages')
        sys.path.append(site_packages)
        with patch_pkgutil_get_loader():
            try:
                import site_package
                self.assert_equal(site_package.app.instance_path,
                                  os.path.join(expected_prefix, 'var',
                                               'site_package-instance'))
            finally:
                sys.prefix = real_prefix
                sys.path.remove(site_packages)
                if 'site_package' in sys.modules:
                    del sys.modules['site_package'] 
Example 31
Project: Flask_Blog   Author: sugarguo   File: config.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def test_egg_installed_paths(self):
        here = os.path.abspath(os.path.dirname(__file__))
        expected_prefix = os.path.join(here, 'test_apps')
        real_prefix, sys.prefix = sys.prefix, expected_prefix
        site_packages = os.path.join(expected_prefix, 'lib', 'python2.5', 'site-packages')
        egg_path = os.path.join(site_packages, 'SiteEgg.egg')
        sys.path.append(site_packages)
        sys.path.append(egg_path)
        try:
            import site_egg # in SiteEgg.egg
            self.assert_equal(site_egg.app.instance_path,
                              os.path.join(expected_prefix, 'var',
                                           'site_egg-instance'))
        finally:
            sys.prefix = real_prefix
            sys.path.remove(site_packages)
            sys.path.remove(egg_path)
            if 'site_egg' in sys.modules:
                del sys.modules['site_egg'] 
Example 32
Project: Flask_Blog   Author: sugarguo   File: easy_install.py    (GNU General Public License v3.0) View Source Project 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 33
Project: pip-update-requirements   Author: alanhamlett   File: util.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def get_resources_dests(resources_root, rules):
    """Find destinations for resources files"""

    def get_rel_path(root, path):
        # normalizes and returns a lstripped-/-separated path
        root = root.replace(os.path.sep, '/')
        path = path.replace(os.path.sep, '/')
        assert path.startswith(root)
        return path[len(root):].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 34
Project: pip-update-requirements   Author: alanhamlett   File: util.py    (BSD 2-Clause "Simplified" License) View Source Project 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 35
Project: pip-update-requirements   Author: alanhamlett   File: outdated.py    (BSD 2-Clause "Simplified" License) View Source Project 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 36
Project: pip-update-requirements   Author: alanhamlett   File: req_install.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def uninstall(self, auto_confirm=False, verbose=False):
        """
        Uninstall the distribution currently satisfying this requirement.

        Prompts before removing or modifying files unless
        ``auto_confirm`` is True.

        Refuses to delete or modify files outside of ``sys.prefix`` -
        thus uninstallation within a virtual environment can only
        modify that virtual environment, even if the virtualenv is
        linked to global site-packages.

        """
        if not self.check_if_exists():
            logger.warning("Skipping %s as it is not installed.", self.name)
            return
        dist = self.satisfied_by or self.conflicts_with

        uninstalled_pathset = UninstallPathSet.from_dist(dist)
        uninstalled_pathset.remove(auto_confirm, verbose)
        return uninstalled_pathset 
Example 37
Project: pip-update-requirements   Author: alanhamlett   File: req_install.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def get_install_args(self, global_options, record_filename, root, prefix):
        install_args = [sys.executable, "-u"]
        install_args.append('-c')
        install_args.append(SETUPTOOLS_SHIM % self.setup_py)
        install_args += list(global_options) + \
            ['install', '--record', record_filename]
        install_args += ['--single-version-externally-managed']

        if root is not None:
            install_args += ['--root', root]
        if prefix is not None:
            install_args += ['--prefix', prefix]

        if self.pycompile:
            install_args += ["--compile"]
        else:
            install_args += ["--no-compile"]

        if running_under_virtualenv():
            py_ver_str = 'python' + sysconfig.get_python_version()
            install_args += ['--install-headers',
                             os.path.join(sys.prefix, 'include', 'site',
                                          py_ver_str, self.name)]

        return install_args 
Example 38
Project: swjtu-pyscraper   Author: Desgard   File: util.py    (MIT License) View Source Project 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 39
Project: swjtu-pyscraper   Author: Desgard   File: util.py    (MIT License) View Source Project 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 40
Project: swjtu-pyscraper   Author: Desgard   File: util.py    (MIT License) View Source Project 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 41
Project: swjtu-pyscraper   Author: Desgard   File: outdated.py    (MIT License) View Source Project 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 42
Project: swjtu-pyscraper   Author: Desgard   File: paths.py    (MIT License) View Source Project 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 43
Project: swjtu-pyscraper   Author: Desgard   File: easy_install.py    (MIT License) View Source Project 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 44
Project: swjtu-pyscraper   Author: Desgard   File: easy_install.py    (MIT License) View Source Project 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 45
Project: swjtu-pyscraper   Author: Desgard   File: easy_install.py    (MIT License) View Source Project 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 46
Project: swjtu-pyscraper   Author: Desgard   File: __init__.py    (MIT License) View Source Project 6 votes vote down vote up
def find_config_files(self):
    found = old_find_config_files(self)
    system_distutils = os.path.join(distutils_path, 'distutils.cfg')
    #if os.path.exists(system_distutils):
    #    found.insert(0, system_distutils)
        # What to call the per-user config file
    if os.name == 'posix':
        user_filename = ".pydistutils.cfg"
    else:
        user_filename = "pydistutils.cfg"
    user_filename = os.path.join(sys.prefix, user_filename)
    if os.path.isfile(user_filename):
        for item in list(found):
            if item.endswith('pydistutils.cfg'):
                found.remove(item)
        found.append(user_filename)
    return found 
Example 47
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: util.py    (MIT License) View Source Project 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 48
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: util.py    (MIT License) View Source Project 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 49
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: util.py    (MIT License) View Source Project 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 50
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: outdated.py    (MIT License) View Source Project 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=(",", ":"))