当前位置: 首页>>代码示例>>Python>>正文


Python TempDirectory.cleanup方法代码示例

本文整理汇总了Python中pip._internal.utils.temp_dir.TempDirectory.cleanup方法的典型用法代码示例。如果您正苦于以下问题:Python TempDirectory.cleanup方法的具体用法?Python TempDirectory.cleanup怎么用?Python TempDirectory.cleanup使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pip._internal.utils.temp_dir.TempDirectory的用法示例。


在下文中一共展示了TempDirectory.cleanup方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: BuildEnvironment

# 需要导入模块: from pip._internal.utils.temp_dir import TempDirectory [as 别名]
# 或者: from pip._internal.utils.temp_dir.TempDirectory import cleanup [as 别名]
class BuildEnvironment(object):
    """Creates and manages an isolated environment to install build deps
    """

    def __init__(self, no_clean):
        self._temp_dir = TempDirectory(kind="build-env")
        self._no_clean = no_clean

    @property
    def path(self):
        return self._temp_dir.path

    def __enter__(self):
        self._temp_dir.create()

        self.save_path = os.environ.get('PATH', None)
        self.save_pythonpath = os.environ.get('PYTHONPATH', None)

        install_scheme = 'nt' if (os.name == 'nt') else 'posix_prefix'
        install_dirs = get_paths(install_scheme, vars={
            'base': self.path,
            'platbase': self.path,
        })

        scripts = install_dirs['scripts']
        if self.save_path:
            os.environ['PATH'] = scripts + os.pathsep + self.save_path
        else:
            os.environ['PATH'] = scripts + os.pathsep + os.defpath

        if install_dirs['purelib'] == install_dirs['platlib']:
            lib_dirs = install_dirs['purelib']
        else:
            lib_dirs = install_dirs['purelib'] + os.pathsep + \
                install_dirs['platlib']
        if self.save_pythonpath:
            os.environ['PYTHONPATH'] = lib_dirs + os.pathsep + \
                self.save_pythonpath
        else:
            os.environ['PYTHONPATH'] = lib_dirs

        return self.path

    def __exit__(self, exc_type, exc_val, exc_tb):
        if not self._no_clean:
            self._temp_dir.cleanup()
        if self.save_path is None:
            os.environ.pop('PATH', None)
        else:
            os.environ['PATH'] = self.save_path

        if self.save_pythonpath is None:
            os.environ.pop('PYTHONPATH', None)
        else:
            os.environ['PYTHONPATH'] = self.save_pythonpath

    def cleanup(self):
        self._temp_dir.cleanup()
开发者ID:edmorley,项目名称:pip,代码行数:60,代码来源:build_env.py

示例2: test_create_and_cleanup_work

# 需要导入模块: from pip._internal.utils.temp_dir import TempDirectory [as 别名]
# 或者: from pip._internal.utils.temp_dir.TempDirectory import cleanup [as 别名]
    def test_create_and_cleanup_work(self):
        tmp_dir = TempDirectory()
        assert tmp_dir.path is None

        tmp_dir.create()
        created_path = tmp_dir.path
        assert tmp_dir.path is not None
        assert os.path.exists(created_path)

        tmp_dir.cleanup()
        assert tmp_dir.path is None
        assert not os.path.exists(created_path)
开发者ID:jonparrott,项目名称:pip,代码行数:14,代码来源:test_utils.py

示例3: EphemWheelCache

# 需要导入模块: from pip._internal.utils.temp_dir import TempDirectory [as 别名]
# 或者: from pip._internal.utils.temp_dir.TempDirectory import cleanup [as 别名]
class EphemWheelCache(SimpleWheelCache):
    """A SimpleWheelCache that creates it's own temporary cache directory
    """

    def __init__(self, format_control):
        self._temp_dir = TempDirectory(kind="ephem-wheel-cache")
        self._temp_dir.create()

        super(EphemWheelCache, self).__init__(
            self._temp_dir.path, format_control
        )

    def cleanup(self):
        self._temp_dir.cleanup()
开发者ID:Black-Thunder01,项目名称:PythonAPI,代码行数:16,代码来源:cache.py

示例4: UninstallPathSet

# 需要导入模块: from pip._internal.utils.temp_dir import TempDirectory [as 别名]
# 或者: from pip._internal.utils.temp_dir.TempDirectory import cleanup [as 别名]

#.........这里部分代码省略.........

        if not verbose:
            will_remove, will_skip = compress_for_output_listing(self.paths)
        else:
            # In verbose mode, display all the files that are going to be
            # deleted.
            will_remove = list(self.paths)
            will_skip = set()

        _display('Would remove:', will_remove)
        _display('Would not remove (might be manually added):', will_skip)
        _display('Would not remove (outside of prefix):', self._refuse)

        return ask('Proceed (y/n)? ', ('y', 'n')) == 'y'

    def rollback(self):
        """Rollback the changes previously made by remove()."""
        if self.save_dir.path is None:
            logger.error(
                "Can't roll back %s; was not uninstalled",
                self.dist.project_name,
            )
            return False
        logger.info('Rolling back uninstall of %s', self.dist.project_name)
        for path in self._moved_paths:
            tmp_path = self._stash(path)
            logger.debug('Replacing %s', path)
            renames(tmp_path, path)
        for pth in self.pth.values():
            pth.rollback()

    def commit(self):
        """Remove temporary save dir: rollback will no longer be possible."""
        self.save_dir.cleanup()
        self._moved_paths = []

    @classmethod
    def from_dist(cls, dist):
        dist_path = normalize_path(dist.location)
        if not dist_is_local(dist):
            logger.info(
                "Not uninstalling %s at %s, outside environment %s",
                dist.key,
                dist_path,
                sys.prefix,
            )
            return cls(dist)

        if dist_path in {p for p in {sysconfig.get_path("stdlib"),
                                     sysconfig.get_path("platstdlib")}
                         if p}:
            logger.info(
                "Not uninstalling %s at %s, as it is in the standard library.",
                dist.key,
                dist_path,
            )
            return cls(dist)

        paths_to_remove = cls(dist)
        develop_egg_link = egg_link_path(dist)
        develop_egg_link_egg_info = '{}.egg-info'.format(
            pkg_resources.to_filename(dist.project_name))
        egg_info_exists = dist.egg_info and os.path.exists(dist.egg_info)
        # Special case for distutils installed package
        distutils_egg_info = getattr(dist._provider, 'path', None)
开发者ID:BenkiKuu,项目名称:pythonip3,代码行数:69,代码来源:req_uninstall.py

示例5: RequirementTracker

# 需要导入模块: from pip._internal.utils.temp_dir import TempDirectory [as 别名]
# 或者: from pip._internal.utils.temp_dir.TempDirectory import cleanup [as 别名]
class RequirementTracker(object):

    def __init__(self):
        # type: () -> None
        self._root = os.environ.get('PIP_REQ_TRACKER')
        if self._root is None:
            self._temp_dir = TempDirectory(delete=False, kind='req-tracker')
            self._temp_dir.create()
            self._root = os.environ['PIP_REQ_TRACKER'] = self._temp_dir.path
            logger.debug('Created requirements tracker %r', self._root)
        else:
            self._temp_dir = None
            logger.debug('Re-using requirements tracker %r', self._root)
        self._entries = set()  # type: Set[InstallRequirement]

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.cleanup()

    def _entry_path(self, link):
        # type: (Link) -> str
        hashed = hashlib.sha224(link.url_without_fragment.encode()).hexdigest()
        return os.path.join(self._root, hashed)

    def add(self, req):
        # type: (InstallRequirement) -> None
        link = req.link
        info = str(req)
        entry_path = self._entry_path(link)
        try:
            with open(entry_path) as fp:
                # Error, these's already a build in progress.
                raise LookupError('%s is already being built: %s'
                                  % (link, fp.read()))
        except IOError as e:
            if e.errno != errno.ENOENT:
                raise
            assert req not in self._entries
            with open(entry_path, 'w') as fp:
                fp.write(info)
            self._entries.add(req)
            logger.debug('Added %s to build tracker %r', req, self._root)

    def remove(self, req):
        # type: (InstallRequirement) -> None
        link = req.link
        self._entries.remove(req)
        os.unlink(self._entry_path(link))
        logger.debug('Removed %s from build tracker %r', req, self._root)

    def cleanup(self):
        # type: () -> None
        for req in set(self._entries):
            self.remove(req)
        remove = self._temp_dir is not None
        if remove:
            self._temp_dir.cleanup()
        logger.debug('%s build tracker %r',
                     'Removed' if remove else 'Cleaned',
                     self._root)

    @contextlib.contextmanager
    def track(self, req):
        # type: (InstallRequirement) -> Iterator[None]
        self.add(req)
        yield
        self.remove(req)
开发者ID:pfmoore,项目名称:pip,代码行数:71,代码来源:req_tracker.py

示例6: InstallRequirement

# 需要导入模块: from pip._internal.utils.temp_dir import TempDirectory [as 别名]
# 或者: from pip._internal.utils.temp_dir.TempDirectory import cleanup [as 别名]

#.........这里部分代码省略.........

        new_location = self.build_location(self._ideal_build_dir)
        if os.path.exists(new_location):
            raise InstallationError(
                'A package already exists in %s; please remove it to continue'
                % display_path(new_location))
        logger.debug(
            'Moving package %s from %s to new location %s',
            self, display_path(old_location), display_path(new_location),
        )
        shutil.move(old_location, new_location)
        self._temp_build_dir.path = new_location
        self._ideal_build_dir = None
        self.source_dir = os.path.normpath(os.path.abspath(new_location))
        self._egg_info_path = None

        # Correct the metadata directory, if it exists
        if self.metadata_directory:
            old_meta = self.metadata_directory
            rel = os.path.relpath(old_meta, start=old_location)
            new_meta = os.path.join(new_location, rel)
            new_meta = os.path.normpath(os.path.abspath(new_meta))
            self.metadata_directory = new_meta

    def remove_temporary_source(self):
        # type: () -> None
        """Remove the source files from this requirement, if they are marked
        for deletion"""
        if self.source_dir and os.path.exists(
                os.path.join(self.source_dir, PIP_DELETE_MARKER_FILENAME)):
            logger.debug('Removing source in %s', self.source_dir)
            rmtree(self.source_dir)
        self.source_dir = None
        self._temp_build_dir.cleanup()
        self.build_env.cleanup()

    def check_if_exists(self, use_user_site):
        # type: (bool) -> bool
        """Find an installed distribution that satisfies or conflicts
        with this requirement, and set self.satisfied_by or
        self.conflicts_with appropriately.
        """
        if self.req is None:
            return False
        try:
            # get_distribution() will resolve the entire list of requirements
            # anyway, and we've already determined that we need the requirement
            # in question, so strip the marker so that we don't try to
            # evaluate it.
            no_marker = Requirement(str(self.req))
            no_marker.marker = None
            self.satisfied_by = pkg_resources.get_distribution(str(no_marker))
            if self.editable and self.satisfied_by:
                self.conflicts_with = self.satisfied_by
                # when installing editables, nothing pre-existing should ever
                # satisfy
                self.satisfied_by = None
                return True
        except pkg_resources.DistributionNotFound:
            return False
        except pkg_resources.VersionConflict:
            existing_dist = pkg_resources.get_distribution(
                self.req.name
            )
            if use_user_site:
                if dist_in_usersite(existing_dist):
开发者ID:pfmoore,项目名称:pip,代码行数:70,代码来源:req_install.py

示例7: BuildEnvironment

# 需要导入模块: from pip._internal.utils.temp_dir import TempDirectory [as 别名]
# 或者: from pip._internal.utils.temp_dir.TempDirectory import cleanup [as 别名]
class BuildEnvironment(object):
    """Creates and manages an isolated environment to install build deps
    """

    def __init__(self):
        self._temp_dir = TempDirectory(kind="build-env")
        self._temp_dir.create()

    @property
    def path(self):
        return self._temp_dir.path

    def __enter__(self):
        self.save_path = os.environ.get('PATH', None)
        self.save_pythonpath = os.environ.get('PYTHONPATH', None)
        self.save_nousersite = os.environ.get('PYTHONNOUSERSITE', None)

        install_scheme = 'nt' if (os.name == 'nt') else 'posix_prefix'
        install_dirs = get_paths(install_scheme, vars={
            'base': self.path,
            'platbase': self.path,
        })

        scripts = install_dirs['scripts']
        if self.save_path:
            os.environ['PATH'] = scripts + os.pathsep + self.save_path
        else:
            os.environ['PATH'] = scripts + os.pathsep + os.defpath

        # Note: prefer distutils' sysconfig to get the
        # library paths so PyPy is correctly supported.
        purelib = get_python_lib(plat_specific=0, prefix=self.path)
        platlib = get_python_lib(plat_specific=1, prefix=self.path)
        if purelib == platlib:
            lib_dirs = purelib
        else:
            lib_dirs = purelib + os.pathsep + platlib
        if self.save_pythonpath:
            os.environ['PYTHONPATH'] = lib_dirs + os.pathsep + \
                self.save_pythonpath
        else:
            os.environ['PYTHONPATH'] = lib_dirs

        os.environ['PYTHONNOUSERSITE'] = '1'

        return self.path

    def __exit__(self, exc_type, exc_val, exc_tb):
        def restore_var(varname, old_value):
            if old_value is None:
                os.environ.pop(varname, None)
            else:
                os.environ[varname] = old_value

        restore_var('PATH', self.save_path)
        restore_var('PYTHONPATH', self.save_pythonpath)
        restore_var('PYTHONNOUSERSITE', self.save_nousersite)

    def cleanup(self):
        self._temp_dir.cleanup()

    def missing_requirements(self, reqs):
        """Return a list of the requirements from reqs that are not present
        """
        missing = []
        with self:
            ws = WorkingSet(os.environ["PYTHONPATH"].split(os.pathsep))
            for req in reqs:
                try:
                    if ws.find(Requirement.parse(req)) is None:
                        missing.append(req)
                except VersionConflict:
                    missing.append(req)
            return missing

    def install_requirements(self, finder, requirements, message):
        args = [
            sys.executable, '-m', 'pip', 'install', '--ignore-installed',
            '--no-user', '--prefix', self.path, '--no-warn-script-location',
        ]
        if logger.getEffectiveLevel() <= logging.DEBUG:
            args.append('-v')
        for format_control in ('no_binary', 'only_binary'):
            formats = getattr(finder.format_control, format_control)
            args.extend(('--' + format_control.replace('_', '-'),
                         ','.join(sorted(formats or {':none:'}))))
        if finder.index_urls:
            args.extend(['-i', finder.index_urls[0]])
            for extra_index in finder.index_urls[1:]:
                args.extend(['--extra-index-url', extra_index])
        else:
            args.append('--no-index')
        for link in finder.find_links:
            args.extend(['--find-links', link])
        for _, host, _ in finder.secure_origins:
            args.extend(['--trusted-host', host])
        if finder.allow_all_prereleases:
            args.append('--pre')
        if finder.process_dependency_links:
            args.append('--process-dependency-links')
#.........这里部分代码省略.........
开发者ID:Black-Thunder01,项目名称:PythonAPI,代码行数:103,代码来源:build_env.py

示例8: BuildEnvironment

# 需要导入模块: from pip._internal.utils.temp_dir import TempDirectory [as 别名]
# 或者: from pip._internal.utils.temp_dir.TempDirectory import cleanup [as 别名]
class BuildEnvironment(object):
    """Creates and manages an isolated environment to install build deps
    """

    def __init__(self):
        # type: () -> None
        self._temp_dir = TempDirectory(kind="build-env")
        self._temp_dir.create()

        self._prefixes = OrderedDict((
            (name, _Prefix(os.path.join(self._temp_dir.path, name)))
            for name in ('normal', 'overlay')
        ))

        self._bin_dirs = []  # type: List[str]
        self._lib_dirs = []  # type: List[str]
        for prefix in reversed(list(self._prefixes.values())):
            self._bin_dirs.append(prefix.bin_dir)
            self._lib_dirs.extend(prefix.lib_dirs)

        # Customize site to:
        # - ensure .pth files are honored
        # - prevent access to system site packages
        system_sites = {
            os.path.normcase(site) for site in (
                get_python_lib(plat_specific=False),
                get_python_lib(plat_specific=True),
            )
        }
        self._site_dir = os.path.join(self._temp_dir.path, 'site')
        if not os.path.exists(self._site_dir):
            os.mkdir(self._site_dir)
        with open(os.path.join(self._site_dir, 'sitecustomize.py'), 'w') as fp:
            fp.write(textwrap.dedent(
                '''
                import os, site, sys

                # First, drop system-sites related paths.
                original_sys_path = sys.path[:]
                known_paths = set()
                for path in {system_sites!r}:
                    site.addsitedir(path, known_paths=known_paths)
                system_paths = set(
                    os.path.normcase(path)
                    for path in sys.path[len(original_sys_path):]
                )
                original_sys_path = [
                    path for path in original_sys_path
                    if os.path.normcase(path) not in system_paths
                ]
                sys.path = original_sys_path

                # Second, add lib directories.
                # ensuring .pth file are processed.
                for path in {lib_dirs!r}:
                    assert not path in sys.path
                    site.addsitedir(path)
                '''
            ).format(system_sites=system_sites, lib_dirs=self._lib_dirs))

    def __enter__(self):
        self._save_env = {
            name: os.environ.get(name, None)
            for name in ('PATH', 'PYTHONNOUSERSITE', 'PYTHONPATH')
        }

        path = self._bin_dirs[:]
        old_path = self._save_env['PATH']
        if old_path:
            path.extend(old_path.split(os.pathsep))

        pythonpath = [self._site_dir]

        os.environ.update({
            'PATH': os.pathsep.join(path),
            'PYTHONNOUSERSITE': '1',
            'PYTHONPATH': os.pathsep.join(pythonpath),
        })

    def __exit__(self, exc_type, exc_val, exc_tb):
        for varname, old_value in self._save_env.items():
            if old_value is None:
                os.environ.pop(varname, None)
            else:
                os.environ[varname] = old_value

    def cleanup(self):
        # type: () -> None
        self._temp_dir.cleanup()

    def check_requirements(self, reqs):
        # type: (Iterable[str]) -> Tuple[Set[Tuple[str, str]], Set[str]]
        """Return 2 sets:
            - conflicting requirements: set of (installed, wanted) reqs tuples
            - missing requirements: set of reqs
        """
        missing = set()
        conflicting = set()
        if reqs:
            ws = WorkingSet(self._lib_dirs)
#.........这里部分代码省略.........
开发者ID:mkurnikov,项目名称:pip,代码行数:103,代码来源:build_env.py

示例9: InstallRequirement

# 需要导入模块: from pip._internal.utils.temp_dir import TempDirectory [as 别名]
# 或者: from pip._internal.utils.temp_dir.TempDirectory import cleanup [as 别名]

#.........这里部分代码省略.........
        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 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

    def remove_temporary_source(self):
        """Remove the source files from this requirement, if they are marked
        for deletion"""
        if self.source_dir and os.path.exists(
                os.path.join(self.source_dir, PIP_DELETE_MARKER_FILENAME)):
            logger.debug('Removing source in %s', self.source_dir)
            rmtree(self.source_dir)
        self.source_dir = None
        self._temp_build_dir.cleanup()
        self.build_env.cleanup()

    def install_editable(self, install_options,
                         global_options=(), prefix=None):
        logger.info('Running setup.py develop for %s', self.name)

        if self.isolated:
            global_options = list(global_options) + ["--no-user-cfg"]

        if prefix:
            prefix_param = ['--prefix={}'.format(prefix)]
            install_options = list(install_options) + prefix_param

        with indent_log():
            # FIXME: should we do --install-headers here too?
            with self.build_env:
                call_subprocess(
                    [
                        sys.executable,
                        '-c',
                        SETUPTOOLS_SHIM % self.setup_py
                    ] +
                    list(global_options) +
                    ['develop', '--no-deps'] +
                    list(install_options),

                    cwd=self.setup_py_dir,
                    show_stdout=False,
                )

        self.install_succeeded = True
开发者ID:Chaoslecion123,项目名称:PythonGroup_11,代码行数:69,代码来源:req_install.py

示例10: BuildEnvironment

# 需要导入模块: from pip._internal.utils.temp_dir import TempDirectory [as 别名]
# 或者: from pip._internal.utils.temp_dir.TempDirectory import cleanup [as 别名]
class BuildEnvironment(object):
    """Creates and manages an isolated environment to install build deps
    """

    def __init__(self, no_clean):
        self._temp_dir = TempDirectory(kind="build-env")
        self._no_clean = no_clean

    @property
    def path(self):
        return self._temp_dir.path

    def __enter__(self):
        self._temp_dir.create()

        self.save_path = os.environ.get('PATH', None)
        self.save_pythonpath = os.environ.get('PYTHONPATH', None)
        self.save_nousersite = os.environ.get('PYTHONNOUSERSITE', None)

        install_scheme = 'nt' if (os.name == 'nt') else 'posix_prefix'
        install_dirs = get_paths(install_scheme, vars={
            'base': self.path,
            'platbase': self.path,
        })

        scripts = install_dirs['scripts']
        if self.save_path:
            os.environ['PATH'] = scripts + os.pathsep + self.save_path
        else:
            os.environ['PATH'] = scripts + os.pathsep + os.defpath

        # Note: prefer distutils' sysconfig to get the
        # library paths so PyPy is correctly supported.
        purelib = get_python_lib(plat_specific=0, prefix=self.path)
        platlib = get_python_lib(plat_specific=1, prefix=self.path)
        if purelib == platlib:
            lib_dirs = purelib
        else:
            lib_dirs = purelib + os.pathsep + platlib
        if self.save_pythonpath:
            os.environ['PYTHONPATH'] = lib_dirs + os.pathsep + \
                self.save_pythonpath
        else:
            os.environ['PYTHONPATH'] = lib_dirs

        os.environ['PYTHONNOUSERSITE'] = '1'

        return self.path

    def __exit__(self, exc_type, exc_val, exc_tb):
        if not self._no_clean:
            self._temp_dir.cleanup()

        def restore_var(varname, old_value):
            if old_value is None:
                os.environ.pop(varname, None)
            else:
                os.environ[varname] = old_value

        restore_var('PATH', self.save_path)
        restore_var('PYTHONPATH', self.save_pythonpath)
        restore_var('PYTHONNOUSERSITE', self.save_nousersite)

    def cleanup(self):
        self._temp_dir.cleanup()
开发者ID:BenkiKuu,项目名称:pythonip3,代码行数:67,代码来源:build_env.py


注:本文中的pip._internal.utils.temp_dir.TempDirectory.cleanup方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。