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


Python bleachbit.FileUtilities类代码示例

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


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

示例1: wipe_swap_linux

def wipe_swap_linux(devices, proc_swaps):
    """Shred the Linux swap file and then reinitilize it"""
    if devices is None:
        return
    if 0 < count_swap_linux():
        raise RuntimeError('Cannot wipe swap while it is in use')
    for device in devices:
        logger.info("wiping swap device '%s'", device)
        safety_limit_bytes = 16 * 1024 ** 3  # 16 gibibytes
        actual_size_bytes = get_swap_size_linux(device, proc_swaps)
        if actual_size_bytes > safety_limit_bytes:
            raise RuntimeError(
                'swap device %s is larger (%d) than expected (%d)' %
                (device, actual_size_bytes, safety_limit_bytes))
        uuid = get_swap_uuid(device)
        # wipe
        FileUtilities.wipe_contents(device, truncate=False)
        # reinitialize
        logger.debug('reinitializing swap device %s', device)
        args = ['mkswap', device]
        if uuid:
            args.append("-U")
            args.append(uuid)
        (rc, _, stderr) = General.run_external(args)
        if 0 != rc:
            raise RuntimeError(stderr.replace("\n", ""))
开发者ID:JulianVolodia,项目名称:bleachbit,代码行数:26,代码来源:Memory.py

示例2: execute

 def execute(self, really_delete):
     """Make changes and return results"""
     if FileUtilities.whitelisted(self.path):
         yield whitelist(self.path)
         return
     ret = {
         # TRANSLATORS: This is the label in the log indicating will be
         # deleted (for previews) or was actually deleted
         'label': _('Delete'),
         'n_deleted': 1,
         'n_special': 0,
         'path': self.path,
         'size': FileUtilities.getsize(self.path)}
     if really_delete:
         try:
             FileUtilities.delete(self.path, self.shred)
         except WindowsError as e:
             # WindowsError: [Error 32] The process cannot access the file because it is being
             # used by another process: u'C:\\Documents and
             # Settings\\username\\Cookies\\index.dat'
             if 32 != e.winerror and 5 != e.winerror:
                 raise
             try:
                 bleachbit.Windows.delete_locked_file(self.path)
             except:
                 raise
             else:
                 if self.shred:
                     import warnings
                     warnings.warn(
                         _('At least one file was locked by another process, so its contents could not be overwritten. It will be marked for deletion upon system reboot.'))
                 # TRANSLATORS: The file will be deleted when the
                 # system reboots
                 ret['label'] = _('Mark for deletion')
     yield ret
开发者ID:tstenner,项目名称:bleachbit,代码行数:35,代码来源:Command.py

示例3: delete_chrome_history

def delete_chrome_history(path):
    """Clean history from History and Favicon files without affecting bookmarks"""
    cols = ('url', 'title')
    where = ""
    ids_int = get_chrome_bookmark_ids(path)
    if ids_int:
        ids_str = ",".join([str(id0) for id0 in ids_int])
        where = "where id not in (%s) " % ids_str
    cmds = __shred_sqlite_char_columns('urls', cols, where)
    cmds += __shred_sqlite_char_columns('visits')
    cols = ('lower_term', 'term')
    cmds += __shred_sqlite_char_columns('keyword_search_terms', cols)
    ver = __get_chrome_history(path)
    if ver >= 20:
        # downloads, segments, segment_usage first seen in Chrome 14,
        #   Google Chrome 15 (database version = 20).
        # Google Chrome 30 (database version 28) doesn't have full_path, but it
        # does have current_path and target_path
        if ver >= 28:
            cmds += __shred_sqlite_char_columns(
                'downloads', ('current_path', 'target_path'))
            cmds += __shred_sqlite_char_columns(
                'downloads_url_chains', ('url', ))
        else:
            cmds += __shred_sqlite_char_columns(
                'downloads', ('full_path', 'url'))
        cmds += __shred_sqlite_char_columns('segments', ('name',))
        cmds += __shred_sqlite_char_columns('segment_usage')
    FileUtilities.execute_sqlite3(path, cmds)
开发者ID:JulianVolodia,项目名称:bleachbit,代码行数:29,代码来源:Special.py

示例4: __is_broken_xdg_desktop_application

def __is_broken_xdg_desktop_application(config, desktop_pathname):
    """Returns boolean whether application deskop entry file is broken"""
    if not config.has_option('Desktop Entry', 'Exec'):
        logger.info("is_broken_xdg_menu: missing required option 'Exec': '%s'", desktop_pathname)
        return True
    exe = config.get('Desktop Entry', 'Exec').split(" ")[0]
    if not FileUtilities.exe_exists(exe):
        logger.info("is_broken_xdg_menu: executable '%s' does not exist '%s'", exe, desktop_pathname)
        return True
    if 'env' == exe:
        # Wine v1.0 creates .desktop files like this
        # Exec=env WINEPREFIX="/home/z/.wine" wine "C:\\Program
        # Files\\foo\\foo.exe"
        execs = shlex.split(config.get('Desktop Entry', 'Exec'))
        wineprefix = None
        del execs[0]
        while True:
            if 0 <= execs[0].find("="):
                (name, value) = execs[0].split("=")
                if 'WINEPREFIX' == name:
                    wineprefix = value
                del execs[0]
            else:
                break
        if not FileUtilities.exe_exists(execs[0]):
            logger.info("is_broken_xdg_menu: executable '%s' does not exist '%s'", execs[0], desktop_pathname)
            return True
        # check the Windows executable exists
        if wineprefix:
            windows_exe = wine_to_linux_path(wineprefix, execs[1])
            if not os.path.exists(windows_exe):
                logger.info("is_broken_xdg_menu: Windows executable '%s' does not exist '%s'",
                            windows_exe, desktop_pathname)
                return True
    return False
开发者ID:JulianVolodia,项目名称:bleachbit,代码行数:35,代码来源:Unix.py

示例5: delete_chrome_favicons

def delete_chrome_favicons(path):
    """Delete Google Chrome and Chromium favicons not use in in history for bookmarks"""

    path_history = os.path.join(os.path.dirname(path), 'History')
    ver = __get_chrome_history(path)
    cmds = ""

    if ver >= 4:
        # Version 4 includes Chromium 12
        # Version 20 includes Chromium 14, Google Chrome 15, Google Chrome 19
        # Version 22 includes Google Chrome 20
        # Version 25 is Google Chrome 26
        # Version 26 is Google Chrome 29
        # Version 28 is Google Chrome 30
        # Version 29 is Google Chrome 37
        # Version 32 is Google Chrome 51
        # Version 36 is Google Chrome 60
        # Version 38 is Google Chrome 64

        # icon_mapping
        cols = ('page_url',)
        where = None
        if os.path.exists(path_history):
            cmds += "attach database \"%s\" as History;" % path_history
            where = "where page_url not in (select distinct url from History.urls)"
        cmds += __shred_sqlite_char_columns('icon_mapping', cols, where)

        # favicon images
        cols = ('image_data', )
        where = "where icon_id not in (select distinct icon_id from icon_mapping)"
        cmds += __shred_sqlite_char_columns('favicon_bitmaps', cols, where)

        # favicons
        # Google Chrome 30 (database version 28): image_data moved to table
        # favicon_bitmaps
        if ver < 28:
            cols = ('url', 'image_data')
        else:
            cols = ('url', )
        where = "where id not in (select distinct icon_id from icon_mapping)"
        cmds += __shred_sqlite_char_columns('favicons', cols, where)
    elif 3 == ver:
        # Version 3 includes Google Chrome 11

        cols = ('url', 'image_data')
        where = None
        if os.path.exists(path_history):
            cmds += "attach database \"%s\" as History;" % path_history
            where = "where id not in(select distinct favicon_id from History.urls)"
        cmds += __shred_sqlite_char_columns('favicons', cols, where)
    else:
        raise RuntimeError('%s is version %d' % (path, ver))

    FileUtilities.execute_sqlite3(path, cmds)
开发者ID:tstenner,项目名称:bleachbit,代码行数:54,代码来源:Special.py

示例6: test_get_sqlite_int

    def test_get_sqlite_int(self):
        """Unit test for get_sqlite_int()"""
        sql = """CREATE TABLE meta(key LONGVARCHAR NOT NULL UNIQUE PRIMARY KEY,value LONGVARCHAR);
INSERT INTO "meta" VALUES('version','20');"""
        # create test file
        filename = self.mkstemp(prefix='bleachbit-test-sqlite')
        FileUtilities.execute_sqlite3(filename, sql)
        self.assertExists(filename)
        # run the test
        ver = Special.get_sqlite_int(filename, 'select value from meta where key="version"')
        self.assertEqual(ver, [20])
开发者ID:az0,项目名称:bleachbit,代码行数:11,代码来源:TestSpecial.py

示例7: start_with_computer

def start_with_computer(enabled):
    """If enabled, create shortcut to start application with computer.
    If disabled, then delete the shortcut."""
    autostart_path = get_autostart_path()
    if not enabled:
        if os.path.lexists(autostart_path):
            FileUtilities.delete(autostart_path)
        return
    if os.path.lexists(autostart_path):
        return
    import winshell
    winshell.CreateShortcut(Path=autostart_path,
                            Target=os.path.join(bleachbit.bleachbit_exe_path, 'bleachbit.exe'))
开发者ID:tstenner,项目名称:bleachbit,代码行数:13,代码来源:Windows.py

示例8: yum_clean

def yum_clean():
    """Run 'yum clean all' and return size in bytes recovered"""
    if os.path.exists('/var/run/yum.pid'):
        msg = _(
            "%s cannot be cleaned because it is currently running.  Close it, and try again.") % "Yum"
        raise RuntimeError(msg)

    old_size = FileUtilities.getsizedir('/var/cache/yum')
    args = ['--enablerepo=*', 'clean', 'all']
    invalid = ['You need to be root', 'Cannot remove rpmdb file']
    run_cleaner_cmd('yum', args, '^unused regex$', invalid)
    new_size = FileUtilities.getsizedir('/var/cache/yum')
    return old_size - new_size
开发者ID:JulianVolodia,项目名称:bleachbit,代码行数:13,代码来源:Unix.py

示例9: delete_mozilla_url_history

def delete_mozilla_url_history(path):
    """Delete URL history in Mozilla places.sqlite (Firefox 3 and family)"""

    cmds = ""

    # delete the URLs in moz_places
    places_suffix = "where id in (select " \
        "moz_places.id from moz_places " \
        "left join moz_bookmarks on moz_bookmarks.fk = moz_places.id " \
        "where moz_bookmarks.id is null); "

    cols = ('url', 'rev_host', 'title')
    cmds += __shred_sqlite_char_columns('moz_places', cols, places_suffix)

    # delete any orphaned annotations in moz_annos
    annos_suffix = "where id in (select moz_annos.id " \
        "from moz_annos " \
        "left join moz_places " \
        "on moz_annos.place_id = moz_places.id " \
        "where moz_places.id is null); "

    cmds += __shred_sqlite_char_columns(
        'moz_annos', ('content', ), annos_suffix)

    # delete any orphaned favicons
    fav_suffix = "where id not in (select favicon_id " \
        "from moz_places where favicon_id is not null ); "

    if __sqlite_table_exists(path, 'moz_favicons'):
        cols = ('url', 'data')
        cmds += __shred_sqlite_char_columns('moz_favicons', cols, fav_suffix)

    # delete any orphaned history visits
    cmds += "delete from moz_historyvisits where place_id not " \
        "in (select id from moz_places where id is not null); "

    # delete any orphaned input history
    input_suffix = "where place_id not in (select distinct id from moz_places)"
    cols = ('input', )
    cmds += __shred_sqlite_char_columns('moz_inputhistory', cols, input_suffix)

    # delete the whole moz_hosts table
    # Reference: https://bugzilla.mozilla.org/show_bug.cgi?id=932036
    # Reference:
    # https://support.mozilla.org/en-US/questions/937290#answer-400987
    if __sqlite_table_exists(path, 'moz_hosts'):
        cmds += __shred_sqlite_char_columns('moz_hosts', ('host',))
        cmds += "delete from moz_hosts;"

    # execute the commands
    FileUtilities.execute_sqlite3(path, cmds)
开发者ID:tstenner,项目名称:bleachbit,代码行数:51,代码来源:Special.py

示例10: delete_chrome_keywords

def delete_chrome_keywords(path):
    """Delete keywords table in Chromium/Google Chrome 'Web Data' database"""
    cols = ('short_name', 'keyword', 'favicon_url',
            'originating_url', 'suggest_url')
    where = "where not date_created = 0"
    cmds = __shred_sqlite_char_columns('keywords', cols, where)
    cmds += "update keywords set usage_count = 0;"
    ver = __get_chrome_history(path, 'Web Data')
    if 43 <= ver < 49:
        # keywords_backup table first seen in Google Chrome 17 / Chromium 17 which is Web Data version 43
        # In Google Chrome 25, the table is gone.
        cmds += __shred_sqlite_char_columns('keywords_backup', cols, where)
        cmds += "update keywords_backup set usage_count = 0;"

    FileUtilities.execute_sqlite3(path, cmds)
开发者ID:JulianVolodia,项目名称:bleachbit,代码行数:15,代码来源:Special.py

示例11: delete_updates

def delete_updates():
    """Returns commands for deleting Windows Updates files"""
    windir = bleachbit.expandvars('$windir')
    dirs = glob.glob(os.path.join(windir, '$NtUninstallKB*'))
    dirs += [bleachbit.expandvars('$windir\\SoftwareDistribution\\Download')]
    dirs += [bleachbit.expandvars('$windir\\ie7updates')]
    dirs += [bleachbit.expandvars('$windir\\ie8updates')]
    if not dirs:
        # if nothing to delete, then also do not restart service
        return

    import win32serviceutil
    wu_running = win32serviceutil.QueryServiceStatus('wuauserv')[1] == 4

    args = ['net', 'stop', 'wuauserv']

    def wu_service():
        General.run_external(args)
        return 0
    if wu_running:
        yield Command.Function(None, wu_service, " ".join(args))

    for path1 in dirs:
        for path2 in FileUtilities.children_in_directory(path1, True):
            yield Command.Delete(path2)
        if os.path.exists(path1):
            yield Command.Delete(path1)

    args = ['net', 'start', 'wuauserv']
    if wu_running:
        yield Command.Function(None, wu_service, " ".join(args))
开发者ID:tstenner,项目名称:bleachbit,代码行数:31,代码来源:Windows.py

示例12: delete_chrome_autofill

def delete_chrome_autofill(path):
    """Delete autofill table in Chromium/Google Chrome 'Web Data' database"""
    cols = ('name', 'value', 'value_lower')
    cmds = __shred_sqlite_char_columns('autofill', cols)
    cols = ('first_name', 'middle_name', 'last_name', 'full_name')
    cmds += __shred_sqlite_char_columns('autofill_profile_names', cols)
    cmds += __shred_sqlite_char_columns('autofill_profile_emails', ('email',))
    cmds += __shred_sqlite_char_columns('autofill_profile_phones', ('number',))
    cols = ('company_name', 'street_address', 'dependent_locality',
            'city', 'state', 'zipcode', 'country_code')
    cmds += __shred_sqlite_char_columns('autofill_profiles', cols)
    cols = (
        'company_name', 'street_address', 'address_1', 'address_2', 'address_3', 'address_4',
        'postal_code', 'country_code', 'language_code', 'recipient_name', 'phone_number')
    cmds += __shred_sqlite_char_columns('server_addresses', cols)
    FileUtilities.execute_sqlite3(path, cmds)
开发者ID:JulianVolodia,项目名称:bleachbit,代码行数:16,代码来源:Special.py

示例13: update_total_size

 def update_total_size(self, bytes_removed):
     """Callback to update the total size cleaned"""
     context_id = self.status_bar.get_context_id('size')
     text = FileUtilities.bytes_to_human(bytes_removed)
     if 0 == bytes_removed:
         text = ""
     self.status_bar.push(context_id, text)
开发者ID:tstenner,项目名称:bleachbit,代码行数:7,代码来源:GUI.py

示例14: get_commands

    def get_commands(self, option_id):
        # paths for which to run expand_glob_join
        egj = []
        if 'recent_documents' == option_id:
            egj.append(
                "user/registry/data/org/openoffice/Office/Histories.xcu")
            egj.append(
                "user/registry/cache/org.openoffice.Office.Histories.dat")

        if 'recent_documents' == option_id and not 'cache' == option_id:
            egj.append("user/registry/cache/org.openoffice.Office.Common.dat")

        for egj_ in egj:
            for prefix in self.prefixes:
                for path in FileUtilities.expand_glob_join(prefix, egj_):
                    if 'nt' == os.name:
                        path = os.path.normpath(path)
                    if os.path.lexists(path):
                        yield Command.Delete(path)

        if 'cache' == option_id:
            dirs = []
            for prefix in self.prefixes:
                dirs += FileUtilities.expand_glob_join(
                    prefix, "user/registry/cache/")
            for dirname in dirs:
                if 'nt' == os.name:
                    dirname = os.path.normpath(dirname)
                for filename in children_in_directory(dirname, False):
                    yield Command.Delete(filename)

        if 'recent_documents' == option_id:
            for prefix in self.prefixes:
                for path in FileUtilities.expand_glob_join(prefix, "user/registry/data/org/openoffice/Office/Common.xcu"):
                    if os.path.lexists(path):
                        yield Command.Function(path,
                                               Special.delete_ooo_history,
                                               _('Delete the usage history'))
                # ~/.openoffice.org/3/user/registrymodifications.xcu
                #       Apache OpenOffice.org 3.4.1 from openoffice.org on Ubuntu 13.04
                # %AppData%\OpenOffice.org\3\user\registrymodifications.xcu
                # Apache OpenOffice.org 3.4.1 from openoffice.org on Windows XP
                for path in FileUtilities.expand_glob_join(prefix, "user/registrymodifications.xcu"):
                    if os.path.lexists(path):
                        yield Command.Function(path,
                                               Special.delete_office_registrymodifications,
                                               _('Delete the usage history'))
开发者ID:tstenner,项目名称:bleachbit,代码行数:47,代码来源:Cleaner.py

示例15: get_globs_size

def get_globs_size(paths):
    """Get the cumulative size (in bytes) of a list of globs"""
    total_size = 0
    for path in paths:
        from glob import iglob
        for p in iglob(path):
            total_size += FileUtilities.getsize(p)
    return total_size
开发者ID:tstenner,项目名称:bleachbit,代码行数:8,代码来源:Unix.py


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