Как назначить номер приоритета для «update-alternatives --config gdm3.css» в одной командной строке?

Я могу выполнить эти команды в терминале:

$ sudo update-alternatives --install /usr/share/gnome-shell/theme/gdm3.css gdm3.css /usr/share/gnome-shell/theme/mytheme/mytheme.css 10
$ sudo update-alternatives --config gdm3.css
There are 2 choices for the alternative gdm3.css (providing /usr/share/gnome-shell/theme/gdm3.css).

  Selection    Path                                                    Priority   Status
------------------------------------------------------------
* 0            /usr/share/gnome-shell/theme/ubuntu.css                  10        auto mode
  1            /usr/share/gnome-shell/theme/mytheme/mytheme.css         10        manual mode
  2            /usr/share/gnome-shell/theme/ubuntu.css                  10        manual mode

Press <enter> to keep the current choice[*], or type selection number: 1
update-alternatives: using /usr/share/gnome-shell/theme/mytheme/mytheme.css to provide /usr/share/gnome-shell/theme/gdm3.css (gdm3.css) in manual mode

Я помещу эти два cmds в python3.6 subprocess.run ().

У меня проблема со второй командой. Как мне присвоить /usr/share/gnome-shell/theme/mytheme/mytheme.css альтернативу gdm3.css в той же cmdline, что и sudo update-alternatives --config gdm3.css?

Кроме того, этот cmd требует ввода номера для выбора mytheme.css. Назначенный номер зависит от назначенного приоритета, что означает, что назначенный номер может быть совершенно произвольным. Как мне преодолеть произвольный характер присвоенного номера?

2
задан 2 October 2019 в 20:34

1 ответ

На основе комментария @PRATAP я разработал это python3.6 решение своего вопроса. Это работало над моей системой Ubuntu 18.04. Я надеюсь, что это может принести пользу другим с той же потребностью.

#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-

from subprocess import run, PIPE
from pathlib import Path
import mimetypes

class CSSFileTypeError(Exception):
    pass

class GDM3_alternatives:
    '''Class to query and configure gdm3.css.

    Argument:
      mytheme - path to my gnome-shell theme .css file.

    Attributes:
      mytheme - path to my gnome-shell theme .css file.
      query   - stdout from "update-alternatives --query gdm3.css" store in a list
      link    - gdm3.css path
      best    - gdm3.css alternative path selected by auto mode 
      value   - current gdm3.css alternative path 
      status  - whether gdm3.css is selected by manual or automatic mode 
      max     - maximum Priority value of all the installed gdm3.css alternatives

    Methods:
      exist()     - determines whether "mytheme" is installed as a gdm3.css alternative.
      configure() - configure "mytheme" file as a gdm3.css alternative.
    '''
    def __init__( self, mytheme=None ):       
        def _get( qvalue ):
            return [ line[ line.index('/') : ] for line in self.query if qvalue in line ][0]
        self.mytheme = mytheme
        self.query = run( [ 'update-alternatives', '--query', 'gdm3.css' ],
                          stdout=PIPE, encoding="utf-8" ).stdout.splitlines()
        self.link   = _get( 'Link:' )
        self.best   = _get( 'Best:' )
        self.value  = _get( 'Value:' )
        self.status = [ line[ line.index(':')+2 : ] for line in self.query if 'Status:' in line ][0]
        self.max = max( [ int( line[ line.index(':')+1 : ] ) for line in self.query if 'Priority:' in line ] )
        #print( f'self.query = {self.query}' )  #For debugging
        #print( f'self.link  = {self.link}' )   #For debugging
        #print( f'self.best  = {self.best}' )   #For debugging
        #print( f'self.value = {self.value}' )  #For debugging
        #print( f'self.status= {self.status}' ) #For debugging
        #print( f'self.max   = {self.max}' )    #For debugging

    def exist( self ):
        '''Method that determines whether "mytheme.css" is installed as a gdm3.css alternative. '''
        if self.mytheme == None:
            raise TypeError( '.css file was not defined.' ) 
        if not Path( self.mytheme ).exists():
            raise FileNotFoundError( f'{self.mytheme} does not exist.' )
        if 'css' not in mimetypes.guess_type( self.mytheme )[0] :
            raise CSSFileTypeError( f'{self.mytheme} is not a css file.' )
        return True in [ True for line in self.query if self.mytheme in line ]

    def configure( self ):
        '''Method to configure my theme ".css" file as a gdm3.css alternative.'''
        def _config():
            if 'auto' not in self.status:
                run( [ 'update-alternatives', '--auto', 'gdm3.css' ] ) #Ensure auto mode is used
            run( [ 'update-alternatives', '--install', self.link, 'gdm3.css', self.mytheme, str(self.max + 1) ] )
            print( f'Configured {self.mytheme} as gdm3.css alternative.' )

        if not self.exist():
            _config()
        elif self.value in self.mytheme:
            print( f'{self.mytheme} is already gdm3.css alternative.' )
        else:
            run( [ 'update-alternatives', '--remove', 'gdm3.css', self.mytheme ] )
            self.__init__( self.mytheme )
            _config()

if __name__ == '__main__':
    #mytheme = '/usr/share/gnome-shell/theme/mytheme/mytheme.css' 
    mytheme = '/usr/share/gnome-shell/theme/mytheme/mytheme.css' #Change this to your theme
    gdm3 = GDM3_alternatives( mytheme )
    gdm3.configure()

## This script needs to be executed by sudo. ## 

, Как использовать этот сценарий:

  1. Сохраняют его в файл с .py расширение, например, myscript.py.
  2. строка Изменения mytheme = '/usr/share/gnome-shell/theme/mytheme/mytheme.css' для показа темы .css путь.
  3. Запущенный скрипт на терминале с sudo разрешением , т.е. тип sudo python3.6 myscript.py. Или откройте свой Python НЕАКТИВНОЕ использование sudo разрешение и запустите этот скрипт Python.

версия update-alternatives в моей системе Ubuntu 18.04:

$ update-alternatives --version
Debian update-alternatives version 1.19.0.5.

This is free software; see the GNU General Public License version 2 or
later for copying conditions. There is NO warranty.
1
ответ дан 23 October 2019 в 09:35

Другие вопросы по тегам:

Похожие вопросы: