ProgramingTip

주어진 파일을 포함하는 파일 시스템의 크기와 여유 공간 찾기

bestdevel 2020. 11. 9. 20:05
반응형

주어진 파일을 포함하는 파일 시스템의 크기와 여유 공간 찾기


Linux에서 Python 2.6을 사용하고 있습니다. 가장 빠른 방법은 무엇입니까?

  • 주어진 디렉토리 나 파일을 포함하는 파티션을 확인 비용?

    를 들어에 예 /dev/sda2마운트되어 /home있고 /dev/mapper/foo에 마운트 되어 있다고 가정합니다 /home/foo. 공유 "/home/foo/bar/baz"에서 쌍을 복구하고 싶습니다 ("/dev/mapper/foo", "home/foo").

  • 그런 다음 주어진 파티션의 사용 통계를 얻으려면? 예를 들어, /dev/mapper/foo파티션의 크기와 사용 가능한 여유 공간 (바이트 단위 또는 메가 바이트 단위)를 싶습니다.


장치에 여유 공간이 필요한 경우 아래 os.statvfs()사용하여 답변을 참조하십시오.

파일과 관련된 장치 이름 및 마운트 지점도 필요하면 외부 프로그램을 호출하여이 정보를 가져와야합니다. df필요한 모든 정보가 제공됩니다. 호출시 df filename파일이 포함 된 파티션에 대한 행을 인쇄합니다.

예를 들면 :

import subprocess
df = subprocess.Popen(["df", "filename"], stdout=subprocess.PIPE)
output = df.communicate()[0]
device, size, used, available, percent, mountpoint = \
    output.split("\n")[1].split()

이것은 df출력 의 정확한 형식에 따라 다르기 때문에 다소 부서지기 쉽지만 더 강력한 솔루션을 줄 알지 못합니다. (아래 /proc파일 시스템에 의존하는 몇 가지 솔루션 이 이보다 이식성이 두렵습니다.)


이 파티션의 이름을 제공하지 않지만 statvfsUnix 시스템 호출을 사용하여 직접 파일 시스템 통계를 얻을 수 있습니다 . Python에서 비용 청구 .os.statvfs('/home/foo/bar/baz')

POSIX에 따른 결과의 관련 필드 :

unsigned long f_frsize   Fundamental file system block size. 
fsblkcnt_t    f_blocks   Total number of blocks on file system in units of f_frsize. 
fsblkcnt_t    f_bfree    Total number of free blocks. 
fsblkcnt_t    f_bavail   Number of free blocks available to 
                         non-privileged process.

따라서 값을 이해하기 위해 f_frsize다음을 곱하십시오 .

import os
statvfs = os.statvfs('/home/foo/bar/baz')

statvfs.f_frsize * statvfs.f_blocks     # Size of filesystem in bytes
statvfs.f_frsize * statvfs.f_bfree      # Actual number of free bytes
statvfs.f_frsize * statvfs.f_bavail     # Number of free bytes that ordinary users
                                        # are allowed to use (excl. reserved space)

import os

def get_mount_point(pathname):
    "Get the mount point of the filesystem containing pathname"
    pathname= os.path.normcase(os.path.realpath(pathname))
    parent_device= path_device= os.stat(pathname).st_dev
    while parent_device == path_device:
        mount_point= pathname
        pathname= os.path.dirname(pathname)
        if pathname == mount_point: break
        parent_device= os.stat(pathname).st_dev
    return mount_point

def get_mounted_device(pathname):
    "Get the device mounted at pathname"
    # uses "/proc/mounts"
    pathname= os.path.normcase(pathname) # might be unnecessary here
    try:
        with open("/proc/mounts", "r") as ifp:
            for line in ifp:
                fields= line.rstrip('\n').split()
                # note that line above assumes that
                # no mount points contain whitespace
                if fields[1] == pathname:
                    return fields[0]
    except EnvironmentError:
        pass
    return None # explicit

def get_fs_freespace(pathname):
    "Get the free space of the filesystem containing pathname"
    stat= os.statvfs(pathname)
    # use f_bfree for superuser, or f_bavail if filesystem
    # has reserved space for superuser
    return stat.f_bfree*stat.f_bsize

내 컴퓨터의 일부 샘플 경로 이름 :

path 'trash':
  mp /home /dev/sda4
  free 6413754368
path 'smov':
  mp /mnt/S /dev/sde
  free 86761562112
path '/usr/local/lib':
  mp / rootfs
  free 2184364032
path '/proc/self/cmdline':
  mp /proc proc
  free 0

추신

Python ≥3.3이면 바이트 shutil.disk_usage(path)(total, used, free)표현 된 명명 된 튜플을 반환 합니다.


Python 3.3부터 표준 라이브러리를 사용하여 수행하는 작업 방법이 있습니다.

$ cat free_space.py 
#!/usr/bin/env python3

import shutil

total, used, free = shutil.disk_usage(__file__)
print(total, used, free)

$ ./free_space.py 
1007870246912 460794834944 495854989312

이 숫자는 바이트 단위입니다. 자세한 내용 은 설명서 를 참조하십시오.


이것은 당신이 요청한 모든 것을 만들 것입니다.

import os
from collections import namedtuple

disk_ntuple = namedtuple('partition',  'device mountpoint fstype')
usage_ntuple = namedtuple('usage',  'total used free percent')

def disk_partitions(all=False):
    """Return all mountd partitions as a nameduple.
    If all == False return phyisical partitions only.
    """
    phydevs = []
    f = open("/proc/filesystems", "r")
    for line in f:
        if not line.startswith("nodev"):
            phydevs.append(line.strip())

    retlist = []
    f = open('/etc/mtab', "r")
    for line in f:
        if not all and line.startswith('none'):
            continue
        fields = line.split()
        device = fields[0]
        mountpoint = fields[1]
        fstype = fields[2]
        if not all and fstype not in phydevs:
            continue
        if device == 'none':
            device = ''
        ntuple = disk_ntuple(device, mountpoint, fstype)
        retlist.append(ntuple)
    return retlist

def disk_usage(path):
    """Return disk usage associated with path."""
    st = os.statvfs(path)
    free = (st.f_bavail * st.f_frsize)
    total = (st.f_blocks * st.f_frsize)
    used = (st.f_blocks - st.f_bfree) * st.f_frsize
    try:
        percent = ret = (float(used) / total) * 100
    except ZeroDivisionError:
        percent = 0
    # NB: the percentage is -5% than what shown by df due to
    # reserved blocks that we are currently not considering:
    # http://goo.gl/sWGbH
    return usage_ntuple(total, used, free, round(percent, 1))


if __name__ == '__main__':
    for part in disk_partitions():
        print part
        print "    %s\n" % str(disk_usage(part.mountpoint))

내 상자에 위의 코드가 인쇄됩니다.

giampaolo@ubuntu:~/dev$ python foo.py 
partition(device='/dev/sda3', mountpoint='/', fstype='ext4')
    usage(total=21378641920, used=4886749184, free=15405903872, percent=22.9)

partition(device='/dev/sda7', mountpoint='/home', fstype='ext4')
    usage(total=30227386368, used=12137168896, free=16554737664, percent=40.2)

partition(device='/dev/sdb1', mountpoint='/media/1CA0-065B', fstype='vfat')
    usage(total=7952400384, used=32768, free=7952367616, percent=0.0)

partition(device='/dev/sr0', mountpoint='/media/WB2PFRE_IT', fstype='iso9660')
    usage(total=695730176, used=695730176, free=0, percent=100.0)

partition(device='/dev/sda6', mountpoint='/media/Dati', fstype='fuseblk')
    usage(total=914217758720, used=614345637888, free=299872120832, percent=67.2)

그것을 찾는 가장 간단한 방법.

import os
from collections import namedtuple

DiskUsage = namedtuple('DiskUsage', 'total used free')

def disk_usage(path):
    """Return disk usage statistics about the given path.

    Will return the namedtuple with attributes: 'total', 'used' and 'free',
    which are the amount of total, used and free space, in bytes.
    """
    st = os.statvfs(path)
    free = st.f_bavail * st.f_frsize
    total = st.f_blocks * st.f_frsize
    used = (st.f_blocks - st.f_bfree) * st.f_frsize
    return DiskUsage(total, used, free)

첫 번째 요점은을 사용 os.path.realpath하여 표준 경로를 가져 와서 /etc/mtab(실제로를 호출하는 것이 getmntent좋지만 정상적인 액세스 방법을 찾을 수 없음) 가장 긴 일치 항목을 찾을 수 있습니다. (확실히, stat파일과 추정 마운트 지점이 실제로 동일한 장치에 있는지 확인해야합니다.)

두 번째 포인트 os.statvfs는 블록 크기 및 사용 정보를 가져 오는 데 사용합니다.

(면책 조항 : 나는 이것 중 아무것도 테스트하지 않았으며 내가 아는 대부분은 coreutils 소스에서 나왔습니다)


질문의 두 번째 부분 인 "주어진 파티션의 사용 통계 가져 오기"에 대해 psutildisk_usage (path) 함수를 사용하여이를 쉽게 수행합니다. 경로가 주어지면 disk_usage()총, 사용 된 공간, 사용 가능한 공간 (바이트)과 사용률을 포함하는 명명 된 튜플을 반환합니다.

문서의 간단한 예 :

>>> import psutil
>>> psutil.disk_usage('/')
sdiskusage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)

Psutil은 2.6에서 3.6까지의 Python 버전과 Linux, Windows 및 OSX에서 작동합니다.


import os

def disk_stat(path):
    disk = os.statvfs(path)
    percent = (disk.f_blocks - disk.f_bfree) * 100 / (disk.f_blocks -disk.f_bfree + disk.f_bavail) + 1
    return percent


print disk_stat('/')
print disk_stat('/data')

일반적으로 /proc디렉토리는 Linux에서 이러한 정보를 포함하며 가상 파일 시스템입니다. 예를 들어, /proc/mounts현재 마운트 된 디스크에 대한 정보를 제공합니다. 직접 파싱 할 수 있습니다. 유틸리티 좋아 top, df모든 메이크업의 사용 /proc.

나는 그것을 사용하지 않았지만 래퍼를 원한다면 이것도 도움이 될 것입니다 : http://bitbucket.org/chrismiles/psi/wiki/Home

참고 URL : https://stackoverflow.com/questions/4260116/find-size-and-free-space-of-the-filesystem-tained-a-given-file

반응형

'ProgramingTip' 카테고리의 다른 글

배열에서 가장 긴 찾기 찾기  (0) 2020.11.09
삼항 연산자? : vs if… else  (0) 2020.11.09
설치 후 awscli가 경로에 추가되지 않음 경고  (0) 2020.11.09
SDK에서 ASCII가 아닌 문자  (0) 2020.11.09
$ 대 jQuery  (0) 2020.11.08