Найти - Пользователи
Полная версия: Обновления кэша пакетов в Linux
Начало » Python для новичков » Обновления кэша пакетов в Linux
1
grandfa8
Ребят, написал небольшой скрипт установки dockera и необходимый софт для его работы.
Проблема вот в чем. После добавления репозитория Докера в sources.list пытаюсь выполнить обновление (cache.update()) и проверяю повился ли после добавления репозитория в кэше пакетов докер (cache).
Пакет docker-ce не появился и выполнение скрипта оканчивается следующей ошибкой:

root@jessie:/home/vagrant# python3 /vagrant/py_deploy_isim_test.py                             
apt-transport-https is installed
ca-certificates is installed
curl is installed
software-properties-common is installed
OK
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/apt/cache.py", line 201, in __getitem__
return self._weakref[key]
File "/usr/lib/python3.4/weakref.py", line 125, in __getitem__
o = self.data[key]()
KeyError: 'docker-ce'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/vagrant/py_deploy_isim_test.py", line 15, in <module>
pkg = cache[pkg_name]
File "/usr/lib/python3/dist-packages/apt/cache.py", line 208, in __getitem__
raise KeyError('The cache has no package named %r' % key)
KeyError: "The cache has no package named 'docker-ce'"

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/apt/cache.py", line 201, in __getitem__
return self._weakref[key]
File "/usr/lib/python3.4/weakref.py", line 125, in __getitem__
o = self.data[key]()
KeyError: 'docker-ce'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/vagrant/py_deploy_isim_test.py", line 40, in <module>
pkg = cache[pkg_name]
File "/usr/lib/python3/dist-packages/apt/cache.py", line 208, in __getitem__
raise KeyError('The cache has no package named %r' % key)
KeyError: "The cache has no package named 'docker-ce'"

После повторного запуска все работает как надо. Есть предположение, что cache.update() смотрит в sources.list, который был в начале выполнения скрипта (до выполнения команд src_list.add…. ). Как сделать так чтобы cache.update() увидел обновленный sources.list?
За любую помощь благодарен!

 #!/usr/bin/python3
import requests
import subprocess
import apt
import aptsources.sourceslist
pkg_list = ['apt-transport-https','ca-certificates','curl','software-properties-common','docker-ce']
cache = apt.cache.Cache()
cache.update()
for pkg_name in pkg_list:
    try:
        pkg = cache[pkg_name]
        if pkg.is_installed:
            print('{0} is installed'.format(pkg_name))
        else:
            pkg.mark_install()
            # try:
            cache.commit()
    except KeyError:
        if pkg_name == 'docker-ce':
            key = requests.get('https://download.docker.com/linux/debian/gpg')
            with open('d_key', 'wb') as d_key:
                d_key.write(key.content)
                d_key.close()
            # find method in apt lib    
            subprocess.call(['apt-key', 'add', 'd_key'])
            # Add  debian backports repository to sourcelist 
            src_list = aptsources.sourceslist.SourcesList()
            src_list.add(type='deb', uri='http://ftp.debian.org/debian', dist='jessie-backports',
                orig_comps=['main'], comment="", pos=-1, file='/etc/apt/sources.list')
            # Add  docker repository to sourcelist 
            src_list.add(type='deb', uri='https://download.docker.com/linux/debian', dist='jessie',
                orig_comps=['stable'], comment="", pos=-1, file='/etc/apt/sources.list')
            src_list.save()
            cache.update()
            pkg = cache[pkg_name]
            print("INFO: Begin Docker instalation...")
            # before install apt-https
            pkg.mark_install()
            cache.commit()
py.user.next
grandfa8
!/usr/bin/python3
Эта строка неправильная, это должен быть комментарий питона.
grandfa8
py.user.next
Сюда криво скопировал, поправил, извиняюсь
py.user.next
grandfa8
  
            with open('d_key', 'wb') as d_key:
                d_key.write(key.content)
                d_key.close()
Не надо вызывать close(), with его сам вызывает.

grandfa8
Как сделать так чтобы cache.update() увидел обновленный sources.list?
Попробуй добавить
  
cache.open(None)

сразу после последнего
  
cache.update()
grandfa8
py.user.next после последнего
 cache.update()
, добавил
 cache.open(None)
не помогло
grandfa8
Всем привет! Дурачился в ipython пытаясь разрешить свою ситуацию в итоге вот такое получилось:
 #!/usr/bin/env python3.4
import requests
import subprocess
import apt
import aptsources.sourceslist
import time
pkg_list = ['ca-certificates', 'curl',
    'software-properties-common', 'docker-ce']
cache = apt.cache.Cache()
for pkg_name in pkg_list:
    try:
        pkg = cache[pkg_name]
        if pkg.is_installed:
            print('{0} is installed'.format(pkg_name))
        else:
            pkg.mark_install()
            cache.commit()
    except KeyError:
        if pkg_name == 'docker-ce':
            key = requests.get('https://download.docker.com/linux/debian/gpg')
            with open('d_key', 'wb') as d_key:
                d_key.write(key.content)
            # find method in apt lib
            subprocess.call(['apt-key', 'add', 'd_key'])
            src_list = aptsources.sourceslist.SourcesList()
            src_list.add(type='deb', uri='http://ftp.debian.org/debian', dist='jessie-backports',
                orig_comps=['main'], comment="", pos=-1, file='/etc/apt/sources.list')
            src_list.add(type='deb', uri='https://download.docker.com/linux/debian', dist='jessie',
                orig_comps=['stable'], comment="", pos=-1, file='/etc/apt/sources.list')
            src_list.save()
            cache.update()
            cache.open(None)
            cache.update()
            cache.open(None)
            pkg = cache[pkg_name]
            print("INFO: Begin Docker instalation...")
            # before install apt-https
            pkg.mark_install()
            cache.commit()

Повторил два раза конструкцию
            
            cache.update()
            cache.open(None)
после внесения изменений в sources.list, т.к. после однократного вызова пакет так и не удавлось найти в кэше apt.
Заработать заработало, но самое печальное, что я не понял как.
Спасибо py.user.next за подсказу по методу open().
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB