81

LinuxでPython 2.6を使用しています。最速の方法は何ですか:

  • 特定のディレクトリまたはファイルを含むパーティションを特定するには?

    たとえば、/dev/sda2が にマウントされ/home、 に/dev/mapper/fooマウントされているとし/home/fooます。文字列から"/home/foo/bar/baz"ペアを復元したいと思い("/dev/mapper/foo", "home/foo")ます。

  • 次に、指定されたパーティションの使用統計を取得するには? たとえば/dev/mapper/foo、パーティションのサイズと使用可能な空き領域 (バイト単位またはおよそメガバイト単位) を取得したいとします。

4

12 に答える 12

130

これはパーティションの名前を示しませんが、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)
于 2012-09-08T03:56:26.463 に答える
50

デバイスの空き容量だけが必要な場合は、以下を使用して回答を参照してください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よりも移植性が低くなります。)

于 2010-11-23T19:53:45.737 に答える
38

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

これらの数値はバイト単位です。詳細については、ドキュメントを参照してください。

于 2016-09-30T20:39:44.277 に答える
25
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

PS

Python ≥3.3 の場合、バイト単位で表現されshutil.disk_usage(path)た名前付きタプルを返すものがあります。(total, used, free)

于 2010-12-27T09:57:23.843 に答える
16

これにより、あなたが尋ねたすべてが次のようになります。

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)
于 2011-06-18T16:54:12.873 に答える
10

それを見つける最も簡単な方法。

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)
于 2015-08-06T13:11:45.853 に答える
6

最初のポイントとして、を使用os.path.realpathして正規パスを取得し、それをチェックして/etc/mtab(実際に呼び出すことをお勧めしgetmntentますが、通常のアクセス方法を見つけることができません)、最長の一致を見つけることができます。(確かにstat、ファイルと推定マウントポイントの両方を使用して、それらが実際に同じデバイス上にあることを確認する必要があります)

2番目のポイントについては、を使用os.statvfsしてブロックサイズと使用法の情報を取得します。

(免責事項:私はこれをテストしていません。私が知っていることのほとんどはcoreutilsソースからのものです)

于 2010-11-23T20:36:49.207 に答える
1

通常、/procディレクトリには Linux でこのような情報が含まれています。これは仮想ファイルシステムです。たとえば、/proc/mounts現在マウントされているディスクに関する情報を提供します。直接解析できます。のようなユーティリティtopdfすべて を利用し/procます。

私はそれを使用していませんが、ラッパーが必要な場合は、これも役立つかもしれません: http://bitbucket.org/chrismiles/psi/wiki/Home

于 2010-11-23T19:50:42.580 に答える
1

Windows PC のディスク使用状況を確認するには、次のようにします。

import psutil

fan = psutil.disk_usage(path="C:/")
print("Available: ", fan.total/1000000000)
print("Used: ", fan.used/1000000000)
print("Free: ", fan.free/1000000000)
print("Percentage Used: ", fan.percent, "%")
于 2020-05-24T16:31:40.173 に答える