Python shutil 模块,disk_usage() 实例源码

我们从Python开源项目中,提取了以下27个代码示例,用于说明如何使用shutil.disk_usage()

项目:kolibri    作者:learningequality    | 项目源码 | 文件源码
def _get_drive_usage(path):
    """
    Use Python libraries to get drive space/usage statistics. Prior to v3.3, use `os.statvfs`;
    on v3.3+, use the more accurate `shutil.disk_usage`.
    """
    if sys.version_info >= (3, 3):
        usage = shutil.disk_usage(path)
        return {
            "total": usage.total,
            "used": usage.used,
            "free": usage.free,
        }
    else:
        # with os.statvfs, we need to multiple block sizes by block counts to get bytes
        stats = os.statvfs(path)
        total = stats.f_frsize * stats.f_blocks
        free = stats.f_frsize * stats.f_bavail
        return {
            "total": total,
            "free": free,
            "used": total - free,
        }
项目:anglerfish    作者:juancarlospaco    | 项目源码 | 文件源码
def check_folder(folder_to_check: str=Path.home().as_posix(),
                 check_space: int=1) -> bool:
    """Check working folder,from argument,for everything that can go wrong."""
    folder = Path(str(folder_to_check))
    m = "Folder {0} ({0!r}) free space {1} ({2} Bytes) of Minimum {3} GigaByte"
    log.debug("Checking Working Folder: {0} ({0!r}).".format(folder))
    if not folder.is_dir():  # What if folder not a folder.
        log.critical("Folder does not exist: {0} ({0!r}).".format(folder))
        return False
    elif not os.access(folder.as_posix(), os.R_OK):  # What if not Readable.
        log.critical("Folder not readable: {0} ({0!r}).".format(folder))
        return False
    elif not os.access(folder.as_posix(), os.W_OK):  # What if not Writable.
        log.critical("Folder not writable: {0} ({0!r}).".format(folder))
        return False
    elif disk_usage and folder.exists() and bool(check_space):
        hdd = int(disk_usage(folder.as_posix()).free)
        if int(hdd / 1_024 / 1_024 / 1_024) >= int(check_space):  # Check_space
            log.info(m.format(folder, bytes2human(hdd), hdd, check_space))
            return True
        else:  # < check_space Gb.
            log.critical(m.format(folder, bytes2human(hdd), hdd, check_space))
            return False
    return False
项目:docker-box    作者:MicroPyramid    | 项目源码 | 文件源码
def disk_size(self):
        x = shutil.disk_usage('/')
        return format(x.total / 1024 / 1024 / 1024, '.2f')
项目:docker-box    作者:MicroPyramid    | 项目源码 | 文件源码
def free_space(self):
        x = shutil.disk_usage('/')
        return format(x.free / 1024 / 1024 / 1024, '.2f')
项目:docker-box    作者:MicroPyramid    | 项目源码 | 文件源码
def used_space(self):
        x = shutil.disk_usage('/')
        return format(x.used / 1024 / 1024 / 1024, '.2f')
项目:nimp    作者:dontnod    | 项目源码 | 文件源码
def _run_check(self, env):
        path = env.root_dir
        wait_time = min(env.delay, 5 * 60) # Check at least every 5 minutes
        total_wait_time = env.delay

        ran_callback = False
        while True:
            total, used, free = shutil.disk_usage(path)
            byte2gib = 1.0 / 1024 / 1024 / 1024
            byte2pct = 100.0 / total
            logging.info('Disk usage on %s: %.2f GiB total, %.2f GiB used (%.2f%%), %.2f GiB free (%.2f%%)',
                         path, total * byte2gib, used * byte2gib, used * byte2pct, free * byte2gib, free * byte2pct)
            free_percent = free * byte2pct
            if not ran_callback and free_percent < env.warning:
                logging.warning('Only %.2f%% free space on disk, trying diskfull hook', free_percent)
                nimp.environment.execute_hook('diskfull', env)
                ran_callback = True
                continue
            if free_percent >= env.warning:
                break
            if free_percent >= env.error:
                logging.warning('Only %.2f%% free space on disk', free_percent)
                break
            if total_wait_time <= 0:
                return False
            logging.warning('Only %.2f%% free on disk, waiting for %d seconds',
                            free_percent, wait_time)
            time.sleep(wait_time)
            total_wait_time -= wait_time
        return True
项目:respeaker_virtualenv    作者:respeaker    | 项目源码 | 文件源码
def test_disk_usage(self):
        usage = psutil.disk_usage(os.getcwd())
        assert usage.total > 0, usage
        assert usage.used > 0, usage
        assert usage.free > 0, usage
        assert usage.total > usage.used, usage
        assert usage.total > usage.free, usage
        assert 0 <= usage.percent <= 100, usage.percent
        if hasattr(shutil, 'disk_usage'):
            # py >= 3.3, see: http://bugs.python.org/issue12442
            shutil_usage = shutil.disk_usage(os.getcwd())
            tolerance = 5 * 1024 * 1024  # 5MB
            self.assertEqual(usage.total, shutil_usage.total)
            self.assertAlmostEqual(usage.free, shutil_usage.free,
                                   delta=tolerance)
            self.assertAlmostEqual(usage.used, shutil_usage.used,
                                   delta=tolerance)

        # if path does not exist OSError ENOENT is expected across
        # all platforms
        fname = tempfile.mktemp()
        try:
            psutil.disk_usage(fname)
        except OSError as err:
            if err.args[0] != errno.ENOENT:
                raise
        else:
            self.fail("OSError not raised")
项目:respeaker_virtualenv    作者:respeaker    | 项目源码 | 文件源码
def test_disk_usage_unicode(self):
        # see: https://github.com/giampaolo/psutil/issues/416
        safe_rmpath(TESTFN_UNICODE)
        self.addCleanup(safe_rmpath, TESTFN_UNICODE)
        os.mkdir(TESTFN_UNICODE)
        psutil.disk_usage(TESTFN_UNICODE)
项目:aioworkers    作者:aioworkers    | 项目源码 | 文件源码
def disk_usage(self):
        return self.loop.run_in_executor(
            self._executor, shutil.disk_usage, self._config.path)
项目:aioworkers    作者:aioworkers    | 项目源码 | 文件源码
def get_free_space(self):
        du = await self.disk_usage()
        return du.free
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_disk_usage(self):
        usage = shutil.disk_usage(os.getcwd())
        self.assertGreater(usage.total, 0)
        self.assertGreater(usage.used, 0)
        self.assertGreaterEqual(usage.free, 0)
        self.assertGreaterEqual(usage.total, usage.used)
        self.assertGreater(usage.total, usage.free)
项目:dcos    作者:dcos    | 项目源码 | 文件源码
def get_disk_free(path):
    '''
    @type path: str

    @rtype tuple
    '''
    return (path, floor(float(shutil.disk_usage(path).free) / MB))
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_disk_usage(self):
        usage = shutil.disk_usage(os.getcwd())
        self.assertGreater(usage.total, 0)
        self.assertGreater(usage.used, 0)
        self.assertGreaterEqual(usage.free, 0)
        self.assertGreaterEqual(usage.total, usage.used)
        self.assertGreater(usage.total, usage.free)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_module_all_attribute(self):
        self.assertTrue(hasattr(shutil, '__all__'))
        target_api = ['copyfileobj', 'copyfile', 'copymode', 'copystat',
                      'copy', 'copy2', 'copytree', 'move', 'rmtree', 'Error',
                      'SpecialFileError', 'ExecError', 'make_archive',
                      'get_archive_formats', 'register_archive_format',
                      'unregister_archive_format', 'get_unpack_formats',
                      'register_unpack_format', 'unregister_unpack_format',
                      'unpack_archive', 'ignore_patterns', 'chown', 'which',
                      'get_terminal_size', 'SameFileError']
        if hasattr(os, 'statvfs') or os.name == 'nt':
            target_api.append('disk_usage')
        self.assertEqual(set(shutil.__all__), set(target_api))
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def test_disk_usage(self):
        usage = psutil.disk_usage(os.getcwd())
        assert usage.total > 0, usage
        assert usage.used > 0, usage
        assert usage.free > 0, usage
        assert usage.total > usage.used, usage
        assert usage.total > usage.free, usage
        assert 0 <= usage.percent <= 100, usage.percent
        if hasattr(shutil, 'disk_usage'):
            # py >= 3.3, see: http://bugs.python.org/issue12442
            shutil_usage = shutil.disk_usage(os.getcwd())
            tolerance = 5 * 1024 * 1024  # 5MB
            self.assertEqual(usage.total, shutil_usage.total)
            self.assertAlmostEqual(usage.free, shutil_usage.free,
                                   delta=tolerance)
            self.assertAlmostEqual(usage.used, shutil_usage.used,
                                   delta=tolerance)

        # if path does not exist OSError ENOENT is expected across
        # all platforms
        fname = tempfile.mktemp()
        try:
            psutil.disk_usage(fname)
        except OSError as err:
            if err.args[0] != errno.ENOENT:
                raise
        else:
            self.fail("OSError not raised")
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def test_disk_usage_unicode(self):
        # see: https://github.com/giampaolo/psutil/issues/416
        safe_rmpath(TESTFN_UNICODE)
        self.addCleanup(safe_rmpath, TESTFN_UNICODE)
        os.mkdir(TESTFN_UNICODE)
        psutil.disk_usage(TESTFN_UNICODE)
项目:FancyWord    作者:EastonLee    | 项目源码 | 文件源码
def test_disk_usage(self):
        usage = psutil.disk_usage(os.getcwd())
        assert usage.total > 0, usage
        assert usage.used > 0, usage
        assert usage.free > 0, usage
        assert usage.total > usage.used, usage
        assert usage.total > usage.free, usage
        assert 0 <= usage.percent <= 100, usage.percent
        if hasattr(shutil, 'disk_usage'):
            # py >= 3.3, see: http://bugs.python.org/issue12442
            shutil_usage = shutil.disk_usage(os.getcwd())
            tolerance = 5 * 1024 * 1024  # 5MB
            self.assertEqual(usage.total, shutil_usage.total)
            self.assertAlmostEqual(usage.free, shutil_usage.free,
                                   delta=tolerance)
            self.assertAlmostEqual(usage.used, shutil_usage.used,
                                   delta=tolerance)

        # if path does not exist OSError ENOENT is expected across
        # all platforms
        fname = tempfile.mktemp()
        try:
            psutil.disk_usage(fname)
        except OSError as err:
            if err.args[0] != errno.ENOENT:
                raise
        else:
            self.fail("OSError not raised")
项目:FancyWord    作者:EastonLee    | 项目源码 | 文件源码
def test_disk_usage_unicode(self):
        # see: https://github.com/giampaolo/psutil/issues/416
        safe_rmpath(TESTFN_UNICODE)
        self.addCleanup(safe_rmpath, TESTFN_UNICODE)
        os.mkdir(TESTFN_UNICODE)
        psutil.disk_usage(TESTFN_UNICODE)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_disk_usage(self):
        usage = shutil.disk_usage(os.getcwd())
        self.assertGreater(usage.total, 0)
        self.assertGreater(usage.used, 0)
        self.assertGreaterEqual(usage.free, 0)
        self.assertGreaterEqual(usage.total, usage.used)
        self.assertGreater(usage.total, usage.free)
项目:zielen    作者:lostatc    | 项目源码 | 文件源码
def disk_usage(self, memoize=True) -> int:
        """Get the total disk usage of the directory and all of its contents.

        Args:
            memoize: Use cached data if available.

        Returns:
            The total disk usage of the directory in bytes.
        """
        paths = self.scan_paths(memoize=memoize)

        total_size = 0
        for path, stat in paths.items():
            total_size += stat.st_blocks * 512
        return total_size
项目:zielen    作者:lostatc    | 项目源码 | 文件源码
def space_avail(self) -> int:
        """Get the available space in the filesystem the directory is in.

        Returns:
            The amount of free space in bytes.
        """
        return shutil.disk_usage(self.path).free
项目:gpt    作者:encarsia    | 项目源码 | 文件源码
def discspace_info(self):
        """Save memory information about disc and card in list [total,used,free], use values to display levelbar and label element below"""

        self.disc_space = [shutil.disk_usage(cli.stdir).total,
                            shutil.disk_usage(cli.stdir).used,
                            shutil.disk_usage(cli.stdir).free]
        if cli.detectcard() is True:
            self.card_space = [shutil.disk_usage(cli.cardpath).total,
                                shutil.disk_usage(cli.cardpath).used,
                                shutil.disk_usage(cli.cardpath).free,True]
        else:
            self.card_space = [1,0,0,False]

        self.disc_bar = self.builder.get_object("level_wdir")
        self.card_bar = self.builder.get_object("level_sd")

        self.disc_bar.add_offset_value("lower",0.5)
        self.disc_bar.add_offset_value("low",0.7)
        self.disc_bar.add_offset_value("high",0.9)

        self.card_bar.add_offset_value("lower",0.4)
        self.card_bar.add_offset_value("low",0.7)
        self.card_bar.add_offset_value("high",0.9)

        self.disc_bar.set_value(self.disc_space[1]/self.disc_space[0])
        self.card_bar.set_value(self.card_space[1]/self.card_space[0])

        self.builder.get_object("free_wdir").set_text(_("free: {0} of {1}").format(self.sizeof_fmt(self.disc_space[2]),self.sizeof_fmt(self.disc_space[0])))
        if self.card_space[3] is True:
            self.builder.get_object("free_sd").set_text(_("free: {0} of {1}").format(self.sizeof_fmt(self.card_space[2]),self.sizeof_fmt(self.card_space[0])))
        else:
            self.builder.get_object("free_sd").set_text("")

    #borrowed from http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
项目:gpt    作者:encarsia    | 项目源码 | 文件源码
def freespace(self,src,dest):
        """Check for free disc space"""
        if self.abs_size < shutil.disk_usage(dest).free:
            return True
        else:
            self.needspace = app.sizeof_fmt(self.abs_size - shutil.disk_usage(dest).free)
            return False

    #Zielordner wählen, neuen oder bestehenden Ordner, Defaultwert yyyy-mm-dd
项目:kolibri    作者:learningequality    | 项目源码 | 文件源码
def get_drive_list():
    """
    Gets a list of drives and metadata by parsing the output of `mount`, and adding additional info from various commands.
    Disk size/usage comes from shutil.disk_usage or os.statvfs, and name/type info from dbus (Linux) or diskutil (OSX).
    """

    if sys.platform == "darwin":
        MOUNT_PARSER = OSX_MOUNT_PARSER
    else:
        MOUNT_PARSER = LINUX_MOUNT_PARSER

    try:
        drivelist = subprocess.Popen('mount', shell=True, stdout=subprocess.PIPE)
        drivelisto, err = drivelist.communicate()
    except OSError:  # couldn't run `mount`, let's try reading the /etc/mounts listing directly
        with open("/proc/mounts") as f:
            drivelisto = f.read()
        MOUNT_PARSER = RAW_MOUNT_PARSER

    drives = []

    for drivematch in MOUNT_PARSER.finditer(drivelisto.decode()):

        drive = drivematch.groupdict()
        path = drive["path"].replace("\\040", " ").replace("\\011", "\t").replace("\\012", "\n").replace("\\134", "\\")

        # skip the drive if the filesystem or path is in a blacklist
        if drive["filesystem"] in FILESYSTEM_BLACKLIST or any(path.startswith(p) for p in PATH_PREFIX_BLACKLIST):
            logger.debug("Skipping blacklisted drive '{}'".format(path))
            continue

        # skip if we don't have read access to the drive
        if not os.access(path, os.R_OK):
            continue

        # attempt to get some additional metadata about the drive
        usage = _get_drive_usage(path)
        dbus_drive_info = _try_to_get_drive_info_from_dbus(drive["device"])
        diskutil_info = _try_to_get_drive_info_from_diskutil(drive["device"])

        # combine the various metadata sources to construct the overall drive metadata
        drives.append({
            "path": path,
            "name": dbus_drive_info.get("name") or diskutil_info.get("name") or path,
            "filesystem": drive["filesystem"],
            "freespace": usage["free"],
            "totalspace": usage["total"],
            "drivetype": dbus_drive_info.get("drivetype") or diskutil_info.get("drivetype") or "",
            "guid": dbus_drive_info.get("guid") or diskutil_info.get("guid") or drive["device"],
        })

    return drives
项目:respeaker_virtualenv    作者:respeaker    | 项目源码 | 文件源码
def test_disk_partitions(self):
        # all = False
        ls = psutil.disk_partitions(all=False)
        # on travis we get:
        #     self.assertEqual(p.cpu_affinity(), [n])
        # AssertionError: Lists differ: [0, 1, 2, 3, 4, 5, 6, 7,... != [0]
        self.assertTrue(ls, msg=ls)
        for disk in ls:
            if WINDOWS and 'cdrom' in disk.opts:
                continue
            if not POSIX:
                assert os.path.exists(disk.device), disk
            else:
                # we cannot make any assumption about this, see:
                # http://goo.gl/p9c43
                disk.device
            if SUNOS:
                # on solaris apparently mount points can also be files
                assert os.path.exists(disk.mountpoint), disk
            else:
                assert os.path.isdir(disk.mountpoint), disk
            assert disk.fstype, disk
            self.assertIsInstance(disk.opts, str)

        # all = True
        ls = psutil.disk_partitions(all=True)
        self.assertTrue(ls, msg=ls)
        for disk in psutil.disk_partitions(all=True):
            if not WINDOWS:
                try:
                    os.stat(disk.mountpoint)
                except OSError as err:
                    if TRAVIS and OSX and err.errno == errno.EIO:
                        continue
                    # http://mail.python.org/pipermail/python-dev/
                    #     2012-June/120787.html
                    if err.errno not in (errno.EPERM, errno.EACCES):
                        raise
                else:
                    if SUNOS:
                        # on solaris apparently mount points can also be files
                        assert os.path.exists(disk.mountpoint), disk
                    else:
                        assert os.path.isdir(disk.mountpoint), disk
            self.assertIsInstance(disk.fstype, str)
            self.assertIsInstance(disk.opts, str)

        def find_mount_point(path):
            path = os.path.abspath(path)
            while not os.path.ismount(path):
                path = os.path.dirname(path)
            return path.lower()

        mount = find_mount_point(__file__)
        mounts = [x.mountpoint.lower() for x in
                  psutil.disk_partitions(all=True)]
        self.assertIn(mount, mounts)
        psutil.disk_usage(mount)
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def test_disk_partitions(self):
        # all = False
        ls = psutil.disk_partitions(all=False)
        # on travis we get:
        #     self.assertEqual(p.cpu_affinity(), [n])
        # AssertionError: Lists differ: [0, 1, 2, 3, 4, 5, 6, 7,... != [0]
        self.assertTrue(ls, msg=ls)
        for disk in ls:
            self.assertIsInstance(disk.device, (str, unicode))
            self.assertIsInstance(disk.mountpoint, (str, unicode))
            self.assertIsInstance(disk.fstype, (str, unicode))
            self.assertIsInstance(disk.opts, (str, unicode))
            if WINDOWS and 'cdrom' in disk.opts:
                continue
            if not POSIX:
                assert os.path.exists(disk.device), disk
            else:
                # we cannot make any assumption about this, see:
                # http://goo.gl/p9c43
                disk.device
            if SUNOS:
                # on solaris apparently mount points can also be files
                assert os.path.exists(disk.mountpoint), disk
            else:
                assert os.path.isdir(disk.mountpoint), disk
            assert disk.fstype, disk

        # all = True
        ls = psutil.disk_partitions(all=True)
        self.assertTrue(ls, msg=ls)
        for disk in psutil.disk_partitions(all=True):
            if not WINDOWS:
                try:
                    os.stat(disk.mountpoint)
                except OSError as err:
                    if TRAVIS and OSX and err.errno == errno.EIO:
                        continue
                    # http://mail.python.org/pipermail/python-dev/
                    #     2012-June/120787.html
                    if err.errno not in (errno.EPERM, errno.EACCES):
                        raise
                else:
                    if SUNOS:
                        # on solaris apparently mount points can also be files
                        assert os.path.exists(disk.mountpoint), disk
                    else:
                        assert os.path.isdir(disk.mountpoint), disk
            self.assertIsInstance(disk.fstype, str)
            self.assertIsInstance(disk.opts, str)

        def find_mount_point(path):
            path = os.path.abspath(path)
            while not os.path.ismount(path):
                path = os.path.dirname(path)
            return path.lower()

        mount = find_mount_point(__file__)
        mounts = [x.mountpoint.lower() for x in
                  psutil.disk_partitions(all=True)]
        self.assertIn(mount, mounts)
        psutil.disk_usage(mount)
项目:FancyWord    作者:EastonLee    | 项目源码 | 文件源码
def test_disk_partitions(self):
        # all = False
        ls = psutil.disk_partitions(all=False)
        # on travis we get:
        #     self.assertEqual(p.cpu_affinity(), [n])
        # AssertionError: Lists differ: [0, 1, 2, 3, 4, 5, 6, 7,... != [0]
        self.assertTrue(ls, msg=ls)
        for disk in ls:
            self.assertIsInstance(disk.device, (str, unicode))
            self.assertIsInstance(disk.mountpoint, (str, unicode))
            self.assertIsInstance(disk.fstype, (str, unicode))
            self.assertIsInstance(disk.opts, (str, unicode))
            if WINDOWS and 'cdrom' in disk.opts:
                continue
            if not POSIX:
                assert os.path.exists(disk.device), disk
            else:
                # we cannot make any assumption about this, see:
                # http://goo.gl/p9c43
                disk.device
            if SUNOS:
                # on solaris apparently mount points can also be files
                assert os.path.exists(disk.mountpoint), disk
            else:
                assert os.path.isdir(disk.mountpoint), disk
            assert disk.fstype, disk

        # all = True
        ls = psutil.disk_partitions(all=True)
        self.assertTrue(ls, msg=ls)
        for disk in psutil.disk_partitions(all=True):
            if not WINDOWS:
                try:
                    os.stat(disk.mountpoint)
                except OSError as err:
                    if TRAVIS and OSX and err.errno == errno.EIO:
                        continue
                    # http://mail.python.org/pipermail/python-dev/
                    #     2012-June/120787.html
                    if err.errno not in (errno.EPERM, errno.EACCES):
                        raise
                else:
                    if SUNOS:
                        # on solaris apparently mount points can also be files
                        assert os.path.exists(disk.mountpoint), disk
                    else:
                        assert os.path.isdir(disk.mountpoint), disk
            self.assertIsInstance(disk.fstype, str)
            self.assertIsInstance(disk.opts, str)

        def find_mount_point(path):
            path = os.path.abspath(path)
            while not os.path.ismount(path):
                path = os.path.dirname(path)
            return path.lower()

        mount = find_mount_point(__file__)
        mounts = [x.mountpoint.lower() for x in
                  psutil.disk_partitions(all=True)]
        self.assertIn(mount, mounts)
        psutil.disk_usage(mount)