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


Python cache.Cache类代码示例

本文整理汇总了Python中apt.cache.Cache的典型用法代码示例。如果您正苦于以下问题:Python Cache类的具体用法?Python Cache怎么用?Python Cache使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


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

示例1: _test

def _test():
    """Test function"""
    from apt.cache import Cache
    from apt.progress import DpkgInstallProgress

    cache = Cache()

    vp = "www-browser"
    #print "%s virtual: %s" % (vp, cache.isVirtualPackage(vp))
    providers = cache.get_providing_packages(vp)
    print "Providers for %s :" % vp
    for pkg in providers:
        print " %s" % pkg.name

    d = DebPackage(sys.argv[1], cache)
    print "Deb: %s" % d.pkgname
    if not d.check():
        print "can't be satified"
        print d._failure_string
    print "missing deps: %s" % d.missing_deps
    print d.required_changes

    print "Installing ..."
    ret = d.install(DpkgInstallProgress())
    print ret

    #s = DscSrcPackage(cache, "../tests/3ddesktop_0.2.9-6.dsc")
    #s.check_dep()
    #print "Missing deps: ",s.missingDeps
    #print "Print required changes: ", s.requiredChanges

    s = DscSrcPackage(cache=cache)
    d = "libc6 (>= 2.3.2), libaio (>= 0.3.96) | libaio1 (>= 0.3.96)"
    print s._satisfy_depends(apt_pkg.parse_depends(d))
开发者ID:AbyssSong,项目名称:python-apt,代码行数:34,代码来源:debfile.py

示例2: __init__

 def __init__(self, options):
     # fixme, do graphic cache check
     self.options = options
     if options.quiet:
         tp = apt.progress.base.OpProgress()
     else:
         tp = apt.progress.text.OpProgress()
     # set architecture to architecture in root-dir
     if options.rootdir and os.path.exists(options.rootdir+"/usr/bin/dpkg"):
         arch = Popen([options.rootdir+"/usr/bin/dpkg",
                       "--print-architecture"],
                      stdout=PIPE,
                      universal_newlines=True).communicate()[0]
         if arch:
             apt_pkg.config.set("APT::Architecture",arch.strip())
     if options.apt_opts:
         for o in options.apt_opts:
             if o.find('=') < 0:
                 sys.stderr.write(_("Configuration items must be specified with a =<value>\n"))
                 sys.exit(1)
             (name, value) = o.split('=', 1)
             try:
                 apt_pkg.config.set(name, value)
             except:
                 sys.stderr.write(_("Couldn't set APT option %s to %s\n") % (name, value))
                 sys.exit(1)
     self._cache = Cache(tp, rootdir=options.rootdir)
开发者ID:frontjang,项目名称:gdebi,代码行数:27,代码来源:GDebiCli.py

示例3: refresh_cache

    def refresh_cache(self):
        cache_date = self.get_cache_date()

        if not self.apt_cache:
            self.apt_cache = Cache()
            self.apt_cache_date = cache_date
        elif cache_date != self.apt_cache_date:
            self.apt_cache.open(None)
            self.apt_cache_date = cache_date
开发者ID:linuxmint,项目名称:mint-common,代码行数:9,代码来源:apt_changelog.py

示例4: openCache

 def openCache(self):
     self._cache = Cache(self.cprogress)
     if self._cache._depcache.broken_count > 0:
         self.error_header = _("Broken dependencies")
         self.error_body = _("Your system has broken dependencies. "
                             "This application can not continue until "
                             "this is fixed. "
                             "To fix it run 'gksudo synaptic' or "
                             "'sudo apt-get install -f' "
                             "in a terminal window.")
         return False
     return True
开发者ID:frontjang,项目名称:gdebi,代码行数:12,代码来源:GDebiCommon.py

示例5: install

def install():
    cache = Cache()
    no_ok_pkg = []
    to_install = []
    for pkg in get_packages():
        print("Installation du paquet : '%s'" % (pkg,))
        if cache.has_key(pkg):
            abs_pkg = cache[pkg]
            if abs_pkg.is_installed:
                print(" - Le paquet est déjà installé")
            else:
                print(" + Le paquet va être installé")
                abs_pkg.mark_install()
                to_install.append(abs_pkg)
        else:
            print("Le paquet demandé n'a pas pu être trouvé")
            no_ok_pkg.append(pkg)
    print("L'opération d'analyse est terminée, seul(s) le(s) paquet(s) \
est(sont) introuvable(s):")
    print(",".join(no_ok_pkg))
    raw_input('On est partie ?')
    abs_pkg.commit(text.TextProgress(),
                   InstallProgress())
开发者ID:tonthon,项目名称:packages,代码行数:23,代码来源:install.py

示例6: _test

def _test():
    # type: () -> None
    """Test function"""
    from apt.cache import Cache
    from apt.progress.base import InstallProgress

    cache = Cache()

    vp = "www-browser"
    print("%s virtual: %s" % (vp, cache.is_virtual_package(vp)))
    providers = cache.get_providing_packages(vp)
    print("Providers for %s :" % vp)
    for pkg in providers:
        print(" %s" % pkg.name)

    d = DebPackage(sys.argv[1], cache)
    print("Deb: %s" % d.pkgname)
    if not d.check():
        print("can't be satified")
        print(d._failure_string)
    print("missing deps: %s" % d.missing_deps)
    print(d.required_changes)

    print(d.filelist)

    print("Installing ...")
    ret = d.install(InstallProgress())
    print(ret)

    #s = DscSrcPackage(cache, "../tests/3ddesktop_0.2.9-6.dsc")
    #s.check_dep()
    #print "Missing deps: ",s.missingDeps
    #print "Print required changes: ", s.requiredChanges

    s = DscSrcPackage(cache=cache)
    ds = "libc6 (>= 2.3.2), libaio (>= 0.3.96) | libaio1 (>= 0.3.96)"
    print(s._satisfy_depends(apt_pkg.parse_depends(ds, False)))
开发者ID:julian-klode,项目名称:python-apt,代码行数:37,代码来源:debfile.py

示例7: do_update

def do_update(mark_only):
    _, progress = query_verbosity()

    log.info("Getting list of eligible packages...")
    cache = Cache(progress)
    f_cache = FilteredCache(cache)
    f_cache.set_filter(NvidiaFilter())
    names = f_cache.keys()

    with unhold(names, cache):
        # mark_only means we just want the side-effects of exiting the
        # unhold() context manager.
        if mark_only:
            return False

        log.info("Updating package list...")
        try:
            cache.update()
        except FetchFailedException, err:
            log.warn(err)
        cache.open(progress)  # Refresh package list

        old_versions = {name: cache[name].installed for name in names}
        log.info("Updating all packages...")
        for name in names:
            if cache[name].is_upgradable:
                cache[name].mark_upgrade()
        cache.commit(None, None)

        log.info("Refreshing package cache...")
        cache.open(progress)
        new_versions = {name: cache[name].installed for name in names}

        log.info("Checking whether packages were upgraded...")
        for name in old_versions:
            if old_versions[name] != new_versions[name]:
                log.info("Kernel module changed")
                return True
        return False
开发者ID:ssokolow,项目名称:profile,代码行数:39,代码来源:update_nvidia.py

示例8: do_install

    def do_install(self, to_install, langpacks=False):
        self.nested_progress_start()

        if langpacks:
            self.db.progress('START', 0, 10, 'ubiquity/langpacks/title')
        else:
            self.db.progress('START', 0, 10, 'ubiquity/install/title')
        self.db.progress('INFO', 'ubiquity/install/find_installables')

        self.progress_region(0, 1)
        fetchprogress = DebconfAcquireProgress(
            self.db, 'ubiquity/install/title',
            'ubiquity/install/apt_indices_starting',
            'ubiquity/install/apt_indices')
        cache = Cache()

        if cache._depcache.broken_count > 0:
            syslog.syslog(
                'not installing additional packages, since there are broken '
                'packages: %s' % ', '.join(broken_packages(cache)))
            self.db.progress('STOP')
            self.nested_progress_end()
            return

        for pkg in to_install:
            mark_install(cache, pkg)

        self.db.progress('SET', 1)
        self.progress_region(1, 10)
        if langpacks:
            fetchprogress = DebconfAcquireProgress(
                self.db, 'ubiquity/langpacks/title', None,
                'ubiquity/langpacks/packages')
            installprogress = DebconfInstallProgress(
                self.db, 'ubiquity/langpacks/title',
                'ubiquity/install/apt_info')
        else:
            fetchprogress = DebconfAcquireProgress(
                self.db, 'ubiquity/install/title', None,
                'ubiquity/install/fetch_remove')
            installprogress = DebconfInstallProgress(
                self.db, 'ubiquity/install/title',
                'ubiquity/install/apt_info',
                'ubiquity/install/apt_error_install')
        chroot_setup(self.target)
        commit_error = None
        try:
            try:
                if not self.commit_with_verify(cache,
                                               fetchprogress, installprogress):
                    fetchprogress.stop()
                    installprogress.finishUpdate()
                    self.db.progress('STOP')
                    self.nested_progress_end()
                    return
            except IOError:
                for line in traceback.format_exc().split('\n'):
                    syslog.syslog(syslog.LOG_ERR, line)
                fetchprogress.stop()
                installprogress.finishUpdate()
                self.db.progress('STOP')
                self.nested_progress_end()
                return
            except SystemError, e:
                for line in traceback.format_exc().split('\n'):
                    syslog.syslog(syslog.LOG_ERR, line)
                commit_error = str(e)
        finally:
            chroot_cleanup(self.target)
        self.db.progress('SET', 10)

        cache.open(None)
        if commit_error or cache._depcache.broken_count > 0:
            if commit_error is None:
                commit_error = ''
            brokenpkgs = broken_packages(cache)
            self.warn_broken_packages(brokenpkgs, commit_error)

        self.db.progress('STOP')

        self.nested_progress_end()
开发者ID:thnguyn2,项目名称:ECE_527_MP,代码行数:81,代码来源:install_misc.py

示例9: generate_blacklist

    def generate_blacklist(self):
        manifest_remove = os.path.join(self.casper_path,
                                       'filesystem.manifest-remove')
        manifest_desktop = os.path.join(self.casper_path,
                                        'filesystem.manifest-desktop')
        manifest = os.path.join(self.casper_path, 'filesystem.manifest')
        if os.path.exists(manifest_remove) and os.path.exists(manifest):
            difference = set()
            with open(manifest_remove) as manifest_file:
                for line in manifest_file:
                    if line.strip() != '' and not line.startswith('#'):
                        pkg = line.split(':')[0]
                        difference.add(pkg.split()[0])
            live_packages = set()
            with open(manifest) as manifest_file:
                for line in manifest_file:
                    if line.strip() != '' and not line.startswith('#'):
                        pkg = line.split(':')[0]
                        live_packages.add(pkg.split()[0])
            desktop_packages = live_packages - difference
        elif os.path.exists(manifest_desktop) and os.path.exists(manifest):
            desktop_packages = set()
            with open(manifest_desktop) as manifest_file:
                for line in manifest_file:
                    if line.strip() != '' and not line.startswith('#'):
                        pkg = line.split(':')[0]
                        desktop_packages.add(pkg.split()[0])
            live_packages = set()
            with open(manifest) as manifest_file:
                for line in manifest_file:
                    if line.strip() != '' and not line.startswith('#'):
                        pkg = line.split(':')[0]
                        live_packages.add(pkg.split()[0])
            difference = live_packages - desktop_packages
        else:
            difference = set()

        cache = Cache()

        use_restricted = True
        try:
            if self.db.get('apt-setup/restricted') == 'false':
                use_restricted = False
        except debconf.DebconfError:
            pass
        if not use_restricted:
            for pkg in cache.keys():
                if (cache[pkg].is_installed and
                        cache[pkg].section.startswith('restricted/')):
                    difference.add(pkg)

        # Keep packages we explicitly installed.
        keep = install_misc.query_recorded_installed()
        arch, subarch = install_misc.archdetect()

        # Less than ideal.  Since we cannot know which bootloader we'll need
        # at file copy time, we should figure out why grub still fails when
        # apt-install-direct is present during configure_bootloader (code
        # removed).
        if arch in ('amd64', 'i386'):
            if subarch == 'efi':
                keep.add('grub-efi')
                keep.add('grub-efi-amd64')
                keep.add('grub-efi-amd64-signed')
                keep.add('shim-signed')
                keep.add('mokutil')
                keep.add('fwupdate-signed')
                install_misc.record_installed(['fwupdate-signed'])
                try:
                    altmeta = self.db.get(
                        'base-installer/kernel/altmeta')
                    if altmeta:
                        altmeta = '-%s' % altmeta
                except debconf.DebconfError:
                    altmeta = ''
                keep.add('linux-signed-generic%s' % altmeta)
            else:
                keep.add('grub')
                keep.add('grub-pc')
        elif (arch in ('armel', 'armhf') and
              subarch in ('omap', 'omap4', 'mx5')):
            keep.add('flash-kernel')
            keep.add('u-boot-tools')
        elif arch == 'powerpc':
            keep.add('yaboot')
            keep.add('hfsutils')

        # Even adding ubiquity as a depends to oem-config-{gtk,kde} doesn't
        # appear to force ubiquity and libdebian-installer4 to copy all of
        # their files, so this does the trick.
        try:
            if self.db.get('oem-config/enable') == 'true':
                keep.add('ubiquity')
        except (debconf.DebconfError, IOError):
            pass

        difference -= install_misc.expand_dependencies_simple(
            cache, keep, difference)

        # Consider only packages that don't have a prerm, and which can
#.........这里部分代码省略.........
开发者ID:Sunderland93,项目名称:ubiquity,代码行数:101,代码来源:install.py

示例10: GDebiCommon

class GDebiCommon(object):

    # cprogress may be different in child classes
    def __init__(self, datadir, options, file=""):
        self.cprogress = None
        self._cache = None
        self.deps = ""
        self.version_info_title = ""
        self.version_info_msg = ""
        self._deb = None
        self._options = options
        self.install = []
        self.remove = []
        self.unauthenticated = 0

    def openCache(self):
        self._cache = Cache(self.cprogress)
        if self._cache._depcache.broken_count > 0:
            self.error_header = _("Broken dependencies")
            self.error_body = _("Your system has broken dependencies. "
                                "This application can not continue until "
                                "this is fixed. "
                                "To fix it run 'gksudo synaptic' or "
                                "'sudo apt-get install -f' "
                                "in a terminal window.")
            return False
        return True

    def open(self, file, downloaded=False):
        file = os.path.abspath(file)
        klass = DebPackage
        if file.endswith(".click"):
            klass = ClickPackage
        try:
            self._deb = klass(file, self._cache, downloaded)
        except (IOError, SystemError, ValueError) as e:
            logging.debug("open failed with %s" % e)
            mimetype=guess_type(file)
            if (mimetype[0] != None and
                mimetype[0] != "application/vnd.debian.binary-package"):
                self.error_header = _("'%s' is not a Debian package") % os.path.basename(file)
                self.error_body = _("The MIME type of this file is '%s' "
                             "and can not be installed on this system.") % mimetype[0]
                return False
            else:
                self.error_header = _("Could not open '%s'") % os.path.basename(file)
                self.error_body = _("The package might be corrupted or you are not "
                             "allowed to open the file. Check the permissions "
                             "of the file.")
                return False

    def compareDebWithCache(self):
        # check if the package is available in the normal sources as well
        res = self._deb.compare_to_version_in_cache(use_installed=False)
        if not self._options.non_interactive and res != DebPackage.VERSION_NONE:
            try:
                pkg = self._cache[self._deb.pkgname]
            except (KeyError, TypeError):
                return

            if self._deb.downloaded:
                self.version_info_title = ""
                self.version_info_msg = ""
                return

            # FIXME: make this strs better
            if res == DebPackage.VERSION_SAME:
                if pkg.candidate and pkg.candidate.downloadable:
                    self.version_info_title = _("Same version is available in a software channel")
                    self.version_info_msg = _("You are recommended to install the software "
                            "from the channel instead.")
            elif res == DebPackage.VERSION_NEWER:
                if pkg.candidate and pkg.candidate.downloadable:
                    self.version_info_title = _("An older version is available in a software channel")
                    self.version_info_msg = _("Generally you are recommended to install "
                            "the version from the software channel, since "
                            "it is usually better supported.")
            elif res == DebPackage.VERSION_OUTDATED:
                if pkg.candidate and pkg.candidate.downloadable:
                    self.version_info_title = _("A later version is available in a software "
                              "channel")
                    self.version_info_msg = _("You are strongly advised to install "
                            "the version from the software channel, since "
                            "it is usually better supported.")

    def compareProvides(self):
        provides = set()
        broken_provides = set()
        try:
            pkg = self._cache[self._deb.pkgname].installed
        except (KeyError, TypeError):
            pkg = None
        if pkg:
            if pkg.provides:
                for p in self._deb.provides:
                    for i in p:
                        provides.add(i[0])
            provides = set(pkg.provides).difference(provides)
            if provides:
                for package in list(self._cache.keys()):
#.........这里部分代码省略.........
开发者ID:frontjang,项目名称:gdebi,代码行数:101,代码来源:GDebiCommon.py

示例11: GDebiCli

class GDebiCli(object):

    def __init__(self, options):
        # fixme, do graphic cache check
        self.options = options
        if options.quiet:
            tp = apt.progress.base.OpProgress()
        else:
            tp = apt.progress.text.OpProgress()
        # set architecture to architecture in root-dir
        if options.rootdir and os.path.exists(options.rootdir+"/usr/bin/dpkg"):
            arch = Popen([options.rootdir+"/usr/bin/dpkg",
                          "--print-architecture"],
                         stdout=PIPE,
                         universal_newlines=True).communicate()[0]
            if arch:
                apt_pkg.config.set("APT::Architecture",arch.strip())
        if options.apt_opts:
            for o in options.apt_opts:
                if o.find('=') < 0:
                    sys.stderr.write(_("Configuration items must be specified with a =<value>\n"))
                    sys.exit(1)
                (name, value) = o.split('=', 1)
                try:
                    apt_pkg.config.set(name, value)
                except:
                    sys.stderr.write(_("Couldn't set APT option %s to %s\n") % (name, value))
                    sys.exit(1)
        self._cache = Cache(tp, rootdir=options.rootdir)

    def open(self, file):
        try:
            if (file.endswith(".deb") or
                "Debian binary package" in Popen(["file", file], stdout=PIPE, universal_newlines=True).communicate()[0]):
                self._deb = DebPackage(file, self._cache)
            elif (file.endswith(".dsc") or
                  os.path.basename(file) == "control"):
                self._deb = DscSrcPackage(file, self._cache)
            else:
                sys.stderr.write(_("Unknown package type '%s', exiting\n") % file)
                sys.exit(1)
        except (IOError,SystemError,ValueError) as e:
            logging.debug("error opening: %s" % e)
            sys.stderr.write(_("Failed to open the software package\n"))
            sys.stderr.write(_("The package might be corrupted or you are not "
                           "allowed to open the file. Check the permissions "
                           "of the file.\n"))
            sys.exit(1)
        # check the deps
        if not self._deb.check():
            sys.stderr.write(_("This package is uninstallable\n"))
            sys.stderr.write(self._deb._failure_string + "\n")
            return False
        return True

    def show_description(self):
        try:
            print(self._deb["Description"])
        except KeyError:
            print(_("No description is available"))

    def show_dependencies(self):
        print(self.get_dependencies_info())

    def get_dependencies_info(self):
        s = ""
        # show what changes
        (install, remove, unauthenticated) = self._deb.required_changes
        if len(unauthenticated) > 0:
            s += _("The following packages are UNAUTHENTICATED: ")
            for pkgname in unauthenticated:
                s += pkgname + " "
        if len(remove) > 0:
            s += _("Requires the REMOVAL of the following packages: ")
            for pkgname in remove:
                s += pkgname + " "
            s += "\n"
        if len(install) > 0:
            s += _("Requires the installation of the following packages: ")
            for pkgname in install:
                s += pkgname + " "
            s += "\n"
        return s

    def install(self):
        # install the dependecnies
        (install,remove,unauthenticated) = self._deb.required_changes
        if len(install) > 0 or len(remove) > 0:
            fprogress = apt.progress.text.AcquireProgress()
            iprogress = apt.progress.base.InstallProgress()
            try:
                self._cache.commit(fprogress,iprogress)
            except(apt.cache.FetchFailedException, SystemError) as e:
                sys.stderr.write(_("Error during install: '%s'") % e)
                return 1

        # install the package itself
        if self._deb.filename.endswith(".dsc"):
            # FIXME: add option to only install build-dependencies
            #        (or build+install the deb) and then enable
#.........这里部分代码省略.........
开发者ID:frontjang,项目名称:gdebi,代码行数:101,代码来源:GDebiCli.py

示例12: prepare

    def prepare(self):
        """Prepare the IsolatedAptCache for use.

        Should be called before use, and after any modification to the list
        of sources.
        """
        self.cleanup()
        logger.debug("Writing apt configs")
        self.tempdir = tempfile.mkdtemp(prefix="hwpack-apt-cache-")
        dirs = ["var/lib/dpkg",
                "etc/apt/sources.list.d",
                "var/cache/apt/archives/partial",
                "var/lib/apt/lists/partial",
                ]
        for d in dirs:
            os.makedirs(os.path.join(self.tempdir, d))
        self.set_installed_packages([], reopen=False)
        sources_list = os.path.join(
            self.tempdir, "etc", "apt", "sources.list")

        with open(sources_list, 'w') as f:
            for source in self.sources:
                # To make a file URL look like an HTTP one (for urlparse)
                # We do this to use urlparse, which is probably more robust
                # than any regexp we come up with.
                mangled_source = source
                if re.search("file:/[^/]", source):
                    mangled_source = re.sub("file:/", "file://", source)

                url_parsed = urlparse.urlsplit(mangled_source)

                # If the source uses authentication, don't put in sources.list
                if url_parsed.password:
                    url_parts_without_user_pass = [url_parsed.scheme,
                                                   url_parsed.hostname,
                                                   url_parsed.path,
                                                   url_parsed.query,
                                                   url_parsed.fragment]

                    auth_name = os.path.join(
                        self.tempdir, "etc", "apt", "auth.conf")
                    with open(auth_name, 'w') as auth:
                        auth.write(
                            "machine " + url_parsed.hostname + "\n" +
                            "login " + url_parsed.username + "\n" +
                            "password " + url_parsed.password + "\n")

                    source = urlparse.urlunsplit(url_parts_without_user_pass)

                    # Get rid of extra / in file URLs
                    source = re.sub("file://", "file:/", source)
                f.write("deb %s\n" % source)

        if self.architecture is not None:
            apt_conf = os.path.join(self.tempdir, "etc", "apt", "apt.conf")
            with open(apt_conf, 'w') as f:
                f.write(
                    'Apt {\nArchitecture "%s";\n'
                    'Install-Recommends "true";\n}\n' % self.architecture)
        if self.prefer_label is not None:
            apt_preferences = os.path.join(
                self.tempdir, "etc", "apt", "preferences")
            with open(apt_preferences, 'w') as f:
                f.write(
                    'Package: *\n'
                    'Pin: release l=%s\n'
                    'Pin-Priority: 1001\n' % self.prefer_label)
        # XXX: This is a temporary workaround for bug 885895.
        apt_pkg.config.set("Dir::bin::dpkg", "/bin/false")
        self.cache = Cache(rootdir=self.tempdir, memonly=True)
        logger.debug("Updating apt cache")
        try:
            self.cache.update()
        except FetchFailedException, e:
            obfuscated_e = re.sub(r"([^ ]https://).+?(@)", r"\1***\2", str(e))
            raise FetchFailedException(obfuscated_e)
开发者ID:pombreda,项目名称:linaro-image-tools-1,代码行数:76,代码来源:packages.py

示例13: _AptChangelog

class _AptChangelog():

    def __init__(self, interactive:bool=False):
        self.interactive = interactive

        # constants
        # apt uses MB rather than MiB, so let's stay consistent
        self.MB = 1000 ** 2
        # downloads larger than this require confirmation or fail
        self.max_download_size_default = 1.5 * self.MB
        self.max_download_size = self.max_download_size_default
        max_download_size_msg_template = "\
To retrieve the full changelog, %s MB have to be downloaded.\n%s\
\n\
Proceed with the download?"
        self.max_download_size_msg_lc = max_download_size_msg_template % ("%.1f",
            "Otherwise we will try to retrieve just the last change.\n")
        self.max_download_size_msg = max_download_size_msg_template % ("%.1f","")
        self.max_download_size_msg_unknown = max_download_size_msg_template % ("an unknown amount of", "")

        self.apt_cache = None
        self.apt_cache_date = None
        self.candidate = None

        # get apt's configuration
        apt_pkg.init_config()
        if apt_pkg.config.exists("Acquire::Changelogs::URI::Origin"):
            self.apt_origins = apt_pkg.config.subtree("Acquire::Changelogs::URI::Origin")
        else:
            self.apt_origins = None
        if apt_pkg.config.exists("Dir::Cache::pkgcache"):
            self.apt_cache_path = apt_pkg.config.find_dir("Dir::Cache")
            self.pkgcache = apt_pkg.config.find_file("Dir::Cache::pkgcache")
        else:
            self.apt_cache = "invalid"
        if (self.apt_cache or
            not os.path.isdir(self.apt_cache_path) or
            not os.path.isfile(self.pkgcache)
            ):
            print("E: Invalid APT configuration found, try to run `apt update` first",
                file=sys.stderr)
            self.close(99)

    def get_cache_date(self):
        if os.path.isfile(self.pkgcache):
            return os.path.getmtime(self.pkgcache)
        return None

    def refresh_cache(self):
        cache_date = self.get_cache_date()

        if not self.apt_cache:
            self.apt_cache = Cache()
            self.apt_cache_date = cache_date
        elif cache_date != self.apt_cache_date:
            self.apt_cache.open(None)
            self.apt_cache_date = cache_date

    def drop_cache(self):
        if self.candidate:
            self.candidate = None
        self.apt_cache = None

    def get_changelog(self, pkg_name:str, no_local:bool=False):
        self.refresh_cache()
        self.candidate = self.parse_package_metadata(pkg_name)

        # parse the package's origin
        if not self.candidate.downloadable:
            origin = "local_package"
        elif self.candidate.origin == "linuxmint":
            origin = "linuxmint"
        elif self.candidate.origin.startswith("LP-PPA-"):
            origin = "LP-PPA"
        elif self.apt_origins and self.candidate.origin in self.apt_origins.list():
            origin = "APT"
        else:
            origin = "unsupported"

        # Check for changelog of installed package first
        has_local_changelog = False
        uri = None
        if not no_local and self.candidate.is_installed:
            if _DEBUG: print("Package is installed...")
            uri = self.get_changelog_from_filelist(
                self.candidate.installed_files, local=True)
            # Ubuntu kernel workarounds
            if self.candidate.origin == "Ubuntu":
                if self.candidate.source_name == "linux-signed":
                    uri = uri.replace("linux-image","linux-modules")
                if self.candidate.source_name == "linux-meta":
                    uri = None
            if uri and not os.path.isfile(uri):
                uri = None

        # Do nothing if local changelog exists
        if uri:
            has_local_changelog = True
        # all origins that APT supports
        elif origin == 'APT':
#.........这里部分代码省略.........
开发者ID:linuxmint,项目名称:mint-common,代码行数:101,代码来源:apt_changelog.py

示例14: error

#        self.apt_status = os.WEXITSTATUS(status)
#        self.finished = True
#
#    def error(self, pkg, errormsg):
#        """Called when an error happens.
#
#        Emits: status_error()
#        """
#        self.emit(QtCore.SIGNAL("status_error()"))

#    def conffile(self, current, new):
#        """Called during conffile.
#
#            Emits: status-conffile()
#        """
#        self.emit("status-conffile")
#
#    def start_update(self):
#        """Called when the update starts.
#
#        Emits: status-started()
#        """
#        self.emit("status-started")

if __name__ =='__main__':
    from apt.cache import Cache
    import apt
    c = Cache(QOpProgress())
    c.update(QAcquireProgress())
    c.commit(QAcquireProgress(), QInstallProgress())
开发者ID:tonthon,项目名称:packages,代码行数:30,代码来源:progress.py

示例15: generate_blacklist

    def generate_blacklist(self):
        manifest_remove = os.path.join(self.casper_path, "filesystem.manifest-remove")
        manifest_desktop = os.path.join(self.casper_path, "filesystem.manifest-desktop")
        manifest = os.path.join(self.casper_path, "filesystem.manifest")
        if os.path.exists(manifest_remove) and os.path.exists(manifest):
            difference = set()
            with open(manifest_remove) as manifest_file:
                for line in manifest_file:
                    if line.strip() != "" and not line.startswith("#"):
                        difference.add(line.split()[0])
            live_packages = set()
            with open(manifest) as manifest_file:
                for line in manifest_file:
                    if line.strip() != "" and not line.startswith("#"):
                        live_packages.add(line.split()[0])
            desktop_packages = live_packages - difference
        elif os.path.exists(manifest_desktop) and os.path.exists(manifest):
            desktop_packages = set()
            with open(manifest_desktop) as manifest_file:
                for line in manifest_file:
                    if line.strip() != "" and not line.startswith("#"):
                        desktop_packages.add(line.split()[0])
            live_packages = set()
            with open(manifest) as manifest_file:
                for line in manifest_file:
                    if line.strip() != "" and not line.startswith("#"):
                        live_packages.add(line.split()[0])
            difference = live_packages - desktop_packages
        else:
            difference = set()

        cache = Cache()

        use_restricted = True
        try:
            if self.db.get("apt-setup/restricted") == "false":
                use_restricted = False
        except debconf.DebconfError:
            pass
        if not use_restricted:
            for pkg in cache.keys():
                if cache[pkg].is_installed and cache[pkg].section.startswith("restricted/"):
                    difference.add(pkg)

        # Keep packages we explicitly installed.
        keep = install_misc.query_recorded_installed()
        arch, subarch = install_misc.archdetect()

        # Less than ideal.  Since we cannot know which bootloader we'll need
        # at file copy time, we should figure out why grub still fails when
        # apt-install-direct is present during configure_bootloader (code
        # removed).
        if arch in ("amd64", "i386"):
            if subarch == "efi":
                keep.add("grub-efi")
                keep.add("grub-efi-amd64")
                efi_vars = "/sys/firmware/efi/vars"
                sb_var = os.path.join(efi_vars, "SecureBoot-8be4df61-93ca-11d2-aa0d-00e098032b8c", "data")
                if os.path.exists(sb_var):
                    with open(sb_var, "rb") as sb_var_file:
                        if sb_var_file.read(1) == b"\x01":
                            keep.add("grub-efi-amd64-signed")
                            keep.add("shim-signed")
                            try:
                                altmeta = self.db.get("base-installer/kernel/altmeta")
                                if altmeta:
                                    altmeta = "-%s" % altmeta
                            except debconf.DebconfError:
                                altmeta = ""
                            keep.add("linux-signed-generic%s" % altmeta)
            else:
                keep.add("grub")
                keep.add("grub-pc")
        elif arch in ("armel", "armhf") and subarch in ("omap", "omap4", "mx5"):
            keep.add("flash-kernel")
            keep.add("u-boot-tools")
        elif arch == "powerpc":
            keep.add("yaboot")
            keep.add("hfsutils")

        # Even adding ubiquity as a depends to oem-config-{gtk,kde} doesn't
        # appear to force ubiquity and libdebian-installer4 to copy all of
        # their files, so this does the trick.
        try:
            if self.db.get("oem-config/enable") == "true":
                keep.add("ubiquity")
        except (debconf.DebconfError, IOError):
            pass

        difference -= install_misc.expand_dependencies_simple(cache, keep, difference)

        # Consider only packages that don't have a prerm, and which can
        # therefore have their files removed without any preliminary work.
        difference = {x for x in difference if not os.path.exists("/var/lib/dpkg/info/%s.prerm" % x)}

        confirmed_remove = set()
        with cache.actiongroup():
            for pkg in sorted(difference):
                if pkg in confirmed_remove:
                    continue
#.........这里部分代码省略.........
开发者ID:27Paolo,项目名称:ubiquity,代码行数:101,代码来源:install.py


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