os.rmdir & os.remove с исключениями в Python частично работает - PullRequest
0 голосов
/ 31 мая 2018

Мой скрипт на Python с os.rmdir (dirs [:]) & os.remove (файлы [:]) с конкретными исключениями, частично работает, НО он удаляет немного слишком много ...

Например, папка / media / также удаляется, но я попытался исключить ее, вот мой пример кода:

def rejuvXvbmc():
    yes_pressed=Common.message_yes_no("[COLOR dodgerblue]"+AddonTitle+"[/COLOR] [COLOR red][B]- Reset![/B][/COLOR]",'Wilt u uw XvBMC \'build\' volledig opschonen (wipe) en Kodi Krypton [B]leeg[/B] her-configureren?','[COLOR dimgray]Please confirm that you wish you wipe clean your current configuration and reconfigure Kodi.[/COLOR]')
    if yes_pressed:
        dp.create("[COLOR white]"+AddonTitle+"[/COLOR] [COLOR red][B]- Reset![/B][/COLOR]",'Snelle XvBMC Krypton reset, even geduld...',' ', '[COLOR dimgray](Quick XvBMC Krypton reset, please wait...)[/COLOR]')
        profileDir=xbmcaddon.Addon(id=addon_id).getAddonInfo('path'); profileDir=xbmc.translatePath(profileDir);
        xbmcPath=os.path.join(profileDir,"..",".."); xbmcPath=os.path.abspath(xbmcPath); Common.log("rejuvXvbmc.main_XvBMC: xbmcPath="+xbmcPath);
        #  Directories and sub directories not to remove but to sort through
        dir_exclude = ('addons','Database','packages','userdata')
        #  Directories and sub directories Directories to ignore and leave intact
        sub_dir_exclude = ('metadata.album.universal','metadata.artists.universal',
                           'metadata.common.imdb.com','metadata.common.musicbrainz.org','metadata.common.theaudiodb.com','metadata.common.themoviedb.org',
                           'metadata.themoviedb.org','metadata.tvdb.com',
                           'plugin.program.super.favourites','plugin.program.xvbmcinstaller.nl','repository.xvbmc','resource.language.nl_nl','script.xvbmc.updatertools','service.xbmc.versioncheck','script.module.xbmc.shared',
                           'skin.aeon.nox.spin','script.grab.fanart','service.library.data.provider','resource.images.recordlabels.white','resource.images.studios.coloured','resource.images.studios.white','xbmc.gui','script.skinshortcuts','script.module.simplejson','script.module.unidecode')
        #  Files to ignore and not to be removed
        file_exclude = ('guisettings.xml','kodi.log','Textures13.db')               ### USE at least 2 files in 'file_exclude'; or else troubles with 'for file in dbAddons:' ###
        #  Log what is excluded and what not...
        Common.log("XvBMC.dir_exclude="+str(dir_exclude)); Common.log("XvBMC.sub_dir_exclude="+str(sub_dir_exclude)); Common.log("XvBMC.file_exclude="+str(file_exclude));
        ###
       #file_exclude = ('Addons27.db','guisettings.xml','kodi.log','Textures13.db') ### USE at least 2 files in 'file_exclude'; or else troubles with 'for file in dbAddons:' ###
        dbList   = os.listdir(databasePath)
        dbAddons = []
        for file in dbList:
            if re.findall('Addons(\d+)\.db', file):
               dbAddons.append(file)
        for file in dbAddons:
            dbFile = os.path.join(databasePath, file)# ie. this can be (re-)used for removal... =databasePath+file #
            try:
                file_exclude = (file,)+file_exclude                                 ### USE at least 2 files in 'file_exclude'; or else troubles with 'for file in dbAddons:' ###
                Common.log("XvBMC.file_exclude_dB="+str(file_exclude))
            except:
                Common.log("XvBMC.file_exclude_dB=EXCEPTION")

        dp.update(11,'','***Clean: files+folders...')

        keep_xvbmc = Common.message_yes_no("[COLOR white][B]"+AddonTitle+"[/B][/COLOR]",'Wilt u het XvBMC-NL basis \'framework\' handhaven na reset? Verwijderd alles behalve XvBMC (aanbeveling).','[COLOR dimgray](do you wish to keep XvBMC\'s default framework?)[/COLOR]')
        if keep_xvbmc: 
            dir_exclude     = ('addon_data','media',)+dir_exclude
            sub_dir_exclude = ('inputstream.rtmp','keymaps','service.subtitles.addic7ed','service.subtitles.opensubtitles_by_opensubtitles','service.subtitles.opensubtitlesBeta','service.subtitles.podnapisi','service.subtitles.subscene','script.module.resolveurl','script.module.urlresolver',)+sub_dir_exclude
            file_exclude    = ('advancedsettings.xml','favourites.xml','profiles.xml','RssFeeds.xml','sources.xml',)+file_exclude
            Common.log("XvBMC.dir_exclude="+str(dir_exclude))
            Common.log("XvBMC.sub_dir_exclude="+str(sub_dir_exclude))
            Common.log("XvBMC.file_exclude="+str(file_exclude))
        else:
            dir_exclude     = ('addon_data',)+dir_exclude
            sub_dir_exclude = ('inputstream.rtmp',)+sub_dir_exclude
            file_exclude    = ('advancedsettings.xml','RssFeeds.xml',)+file_exclude
            Common.log("XvBMC.dir_exclude="+str(dir_exclude))
            Common.log("XvBMC.sub_dir_exclude="+str(sub_dir_exclude))
            Common.log("XvBMC.file_exclude="+str(file_exclude))
            Superfavo       = xbmc.translatePath(os.path.join(USERADDONDATA,'plugin.program.super.favourites','Super Favourites'))
            SkinShrtct      = xbmc.translatePath(os.path.join(USERDATA,'addon_data','script.skinshortcuts'))
            try:
                shutil.rmtree(Superfavo)    #;Common.log("rejuvXvbmc.keep_xvbmc: XvBMC vOoDoO -4- " + str(Superfavo))
            except Exception as e: Common.log("rejuvXvbmc.keep_xvbmc: XvBMC-vOoDoO @ " + str(e))
            try:
                shutil.rmtree(SkinShrtct)   #;Common.log("rejuvXvbmc.keep_xvbmc: XvBMC vOoDoO -4- " + str(SkinShrtct))
            except Exception as e: Common.log("rejuvXvbmc.keep_xvbmc: XvBMC-vOoDoO @ " + str(e))
        try:
            for root, dirs, files in os.walk(xbmcPath,topdown=True):
                dirs[:] = [dir for dir in dirs if dir not in sub_dir_exclude]
                files[:] = [file for file in files if file not in file_exclude]
                for file_name in files: 
                    try:
                        dp.update(33,'','***Cleaning files...')
                       #os.remove(os.path.join(root,file_name))
                        Common.log(os.path.join(root,file_name))
                    except Exception as e: Common.log("rejuvXvbmc.file_name: User files partially removed - " + str(e))
                for folder in dirs:
                    if folder not in dir_exclude:
                        try:
                            dp.update(33,'','***Cleaning folders...')
                           #os.rmdir(os.path.join(root,folder))
                            Common.log(os.path.join(root,folder))
                        except Exception as e: Common.log("rejuvXvbmc.folder: User folders partially removed - " + str(e))
            dp.update(66,'','***Crap Cleaning...')
            Common.REMOVE_EMPTY_FOLDERS(); Common.REMOVE_EMPTY_FOLDERS();
            xbmc.sleep(333)
            Common.REMOVE_EMPTY_FOLDERS(); Common.REMOVE_EMPTY_FOLDERS();
            xbmc.sleep(666)
        except Exception as e:
            Common.log("rejuvXvbmc: User stuff partially removed - " + str(e))
            Common.message("[COLOR dodgerblue]"+AddonTitle+"[/COLOR] [COLOR red][B]- Error![/B][/COLOR]",'...DAT ging niet helemaal goed, controleer uw log...','[COLOR dimgray](XvBMC user files partially removed, please check log)[/COLOR]')
            sys.exit()
        dp.update(99,'','***Cleaning Crap...')
        Common.REMOVE_EMPTY_FOLDERS(); Common.REMOVE_EMPTY_FOLDERS(); Common.REMOVE_EMPTY_FOLDERS(); Common.REMOVE_EMPTY_FOLDERS(); Common.REMOVE_EMPTY_FOLDERS(); Common.REMOVE_EMPTY_FOLDERS();
        xbmc.sleep(999)
        dp.close()
        dialog.ok("[COLOR dodgerblue]"+AddonTitle+"[/COLOR] [COLOR lime][B]- Reboot![/B][/COLOR]", 'Kodi zal nu afsluiten',' ','[COLOR dimgray](shutdown Kodi now)[/COLOR]')
       #os._exit(1)
    else: dialog.ok("[COLOR dodgerblue]"+AddonTitle+"[/COLOR] [COLOR red][B]- Cancelled![/B][/COLOR]",'Er is geen schone installatie gedaan...',' ','[COLOR dimgray](interrupted by user)[/COLOR]')

Здесь я исключил папку de \ media \:

if keep_xvbmc: 
    dir_exclude     = ('addon_data','media',)+dir_exclude

Я думаю, что проблема в этой части ???

for file_name in files:

Этот , вероятно, тоже удаляеттем более, что папка / media / get также полностью пуста, и поэтому она удаляется? Common.REMOVE_EMPTY_FOLDERS () удаляет только полностью пусто осталось за кадром.

Должен ли я каким-либо образом интегрировать dir_exclude в это место?(в / под для file_name в файлах: ), я пытаюсь, но я не могу понять это : '(

Я также пробовал это, теперь папка / media / не запуталась, но теперь слишком много папок продолжают существовать:

        for file_name in files:
            if not any(root.find(f) for f in dir_exclude):
                try:
                    dp.update(33,'','***Cleaning files...')
                    os.remove(os.path.join(root,file_name))
                   #Common.log(os.path.join(root,file_name))
                except Exception as e: Common.log("rejuvXvbmc.file_name: User files partially removed - " + str(e))

L - как вы можете видеть, я добавил следующую строку:

if not any(root.find(f) for f in dir_exclude):

Когда я добавляю 'media' в sub_dir_exclude, все папки с 'media' пропускаются, это тоже не то, что мне нужно, только папка ' media ' в xbmcPath должнабыть сохраненным (пропущено из удаления).

xbmcPath - это моя корневая / стартовая папка, это "своего рода то же самое", что и: xbmc.translatePath ('special: // home/ ') , с этого момента я делаю os.walk (xbmcPath, topdown = True) .

1 Ответ

0 голосов
/ 05 июня 2018

Неважно, это вытащил трюк:

if len(bestanden) > 1:
    vh = dialog.select('Selecteer bestand om te downloaden', bestanden)
    if vh == -1:
        return
else:
    vh = 0
...