【问题标题】:How to get total disk size on Windows?如何在 Windows 上获取总磁盘大小?
【发布时间】:2017-12-06 00:48:59
【问题描述】:

我可以使用ctypesMEMORYSTATUSEX() 来确定 RAM 大小,但我无法找到任何关于总磁盘大小的信息(不是可用空间,而是一般的总容量)。

【问题讨论】:

  • 我想你可以找到答案here
  • @LexHobbit 那是用于 RAM(内存),而不是磁盘。
  • 哦,对不起,你已经写过这个=)
  • 您可以在 Python 3.3+ 中调用 shutil.disk.usage。如果 Python 2 需要它,可以使用 ctypes。
  • @ErykSun 这应该是一个答案 - 最好的答案。 (虽然你打错了 - 它是shutil.disk_usage。)

标签: python windows python-3.x winapi disk


【解决方案1】:

ActiveState 有一个 recipe 用于此,它使用 Windows GetDiskFreeSpaceEx 函数。当我进行一些有限的测试时,它似乎可以工作,但是它有许多潜在的问题,所以这里有一个大大改进且更加防弹的版本,至少在 Python 2.7+ 到 3.x 中工作)并且只使用内置 -在模块中。

@Eryk Sun 应该为这些增强功能获得大部分功劳/责备,因为他显然是使用 ctypes 主题的专家。

import os
import collections
import ctypes
import sys

import locale
locale.setlocale(locale.LC_ALL, '')  # set locale to default to get thousands separators

PULARGE_INTEGER = ctypes.POINTER(ctypes.c_ulonglong)  # Pointer to large unsigned integer
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
kernel32.GetDiskFreeSpaceExW.argtypes = (ctypes.c_wchar_p,) + (PULARGE_INTEGER,) * 3

class UsageTuple(collections.namedtuple('UsageTuple', 'total, used, free')):
    def __str__(self):
        # Add thousands separator to numbers displayed
        return self.__class__.__name__ + '(total={:n}, used={:n}, free={:n})'.format(*self)

def disk_usage(path):
    if sys.version_info < (3,):  # Python 2?
        saved_conversion_mode = ctypes.set_conversion_mode('mbcs', 'strict')
    else:
        try:
            path = os.fsdecode(path)  # allows str or bytes (or os.PathLike in Python 3.6+)
        except AttributeError:  # fsdecode() not added until Python 3.2
            pass

    # Define variables to receive results when passed as "by reference" arguments
    _, total, free = ctypes.c_ulonglong(), ctypes.c_ulonglong(), ctypes.c_ulonglong()

    success = kernel32.GetDiskFreeSpaceExW(
                            path, ctypes.byref(_), ctypes.byref(total), ctypes.byref(free))
    if not success:
        error_code = ctypes.get_last_error()

    if sys.version_info < (3,):  # Python 2?
        ctypes.set_conversion_mode(*saved_conversion_mode)  # restore conversion mode

    if not success:
        windows_error_message = ctypes.FormatError(error_code)
        raise ctypes.WinError(error_code, '{} {!r}'.format(windows_error_message, path))

    used = total.value - free.value
    return UsageTuple(total.value, used, free.value)

if __name__ == '__main__':
    print(disk_usage('C:/'))

示例输出:

UsageTuple(total=102,025,392,128, used=66,308,366,336, free=35,717,025,792)

【讨论】:

    【解决方案2】:

    那么你应该使用这个代码。

    import win32com.client as com
    
    
    def TotalSize(drive):
        """ Return the TotalSize of a shared drive [GB]"""
        try:
            fso = com.Dispatch("Scripting.FileSystemObject")
            drv = fso.GetDrive(drive)
            return drv.TotalSize/2**30
        except:
            return 0
    
    def FreeSpace(drive):
        """ Return the FreeSape of a shared drive [GB]"""
        try:
            fso = com.Dispatch("Scripting.FileSystemObject")
            drv = fso.GetDrive(drive)
            return drv.FreeSpace/2**30
        except:
            return 0
    
    drive = r'C:'
    print 'TotalSize of %s = %d GB' % (drive, TotalSize(drive))
    print 'FreeSapce on %s = %d GB' % (drive, FreeSapce(drive))
    

    【讨论】:

    • 在 Python3 上返回 0
    • 我认为你至少应该提到它需要安装第三方pywin32 模块。
    【解决方案3】:

    您可以使用 psutil,如果您想查找 C: 驱动器或任何其他驱动器的总大小,则只需在 disk_usage() 函数中提供路径并转换为 GB。在这里我找到了 C: Drive 的总磁盘大小。

    import psutil
    totalsize = psutil.disk_usage('C:').total / 2**30
    print('totalsize: ',totalsize, ' GB')
    

    【讨论】:

    • 我觉得你至少应该提一下psutil不在标准库中,必须下载安装。
    【解决方案4】:

    从 Python 3.3 开始,您可以使用shutil.disk_usage()

    import shutil
    print(shutil.disk_usage("E:\\"))
    

    示例输出(E: 是 8GB SD 卡):

    usage(total=7985954816, used=852361216, free=7133593600)
    

    这具有在 Windows 和 Unix 上都可以工作的优点,并且不需要安装 3rd-party 库!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-15
      • 2011-04-14
      • 1970-01-01
      • 2013-03-01
      • 2023-04-04
      • 2021-09-05
      • 2020-08-02
      相关资源
      最近更新 更多