Trova dimensioni e lo spazio libero del filesystem che contiene un dato file
-
27-09-2019 - |
Domanda
Sto usando Python 2.6 su Linux. Qual è il modo più veloce:
-
per determinare quale partizione contiene una determinata directory o un file?
Per esempio, supponiamo che
/dev/sda2
è montato su/home
, e/dev/mapper/foo
è montato su/home/foo
. Dal"/home/foo/bar/baz"
stringa vorrei recuperare la coppia di("/dev/mapper/foo", "home/foo")
. -
e poi, per ottenere statistiche di utilizzo della partizione data? Ad esempio, dato
/dev/mapper/foo
desidero ottenere le dimensioni della partizione e lo spazio libero disponibile (sia in byte o approssimativamente in megabyte).
Soluzione
Se avete solo bisogno lo spazio libero su un dispositivo, vedere la risposta utilizzando os.statvfs()
qui sotto.
Se hai bisogno anche il nome del dispositivo e il punto associato al file monta, si dovrebbe chiamare un programma esterno per ottenere queste informazioni. df
fornirà tutte le informazioni necessarie -. quando viene chiamato come df filename
esso stampa una linea sulla partizione che contiene il file
Per fare un esempio:
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()
Si noti che questo è piuttosto fragile, poiché dipende dal formato esatto dell'uscita df
, ma io non sono a conoscenza di una soluzione più robusta. (Ci sono alcune soluzioni basandosi sul filesystem /proc
sotto che sono ancora meno portabile di questo.)
Altri suggerimenti
Questo non dà il nome della partizione, ma è possibile ottenere le statistiche del file system direttamente utilizzando il statvfs
chiamata di sistema Unix. Per chiamare da Python, utilizzare os.statvfs('/home/foo/bar/baz')
.
I campi rilevanti nel risultato, secondo 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.
Quindi, per dare un senso dei valori, moltiplicare per 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
Alcuni percorsi di esempio sul mio computer:
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
se su Python ≥3.3, c'è shutil.disk_usage(path)
che restituisce un nome tupla di (total, used, free)
espressa in byte.
A partire da Python 3.3, c'è un modo semplice e diretto per fare questo con la libreria standard:
$ 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
Questi numeri sono in byte. Vedere la documentazione per maggiori informazioni.
Questo dovrebbe rendere tutto lei ha chiesto:
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))
Sulla mia casella il codice di cui sopra stampe:
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)
Il modo più semplice per scoprire che.
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)
Per il primo punto, è possibile provare a utilizzare os.path.realpath
per ottenere un percorso canonico, check it contro /etc/mtab
(mi piacerebbe davvero suggerire chiamando getmntent
, ma non riesco a trovare un modo normale per accedervi) per trovare la corrispondenza più lunga. (A dire il vero, probabilmente si dovrebbe stat
sia il file e il punto di montaggio presunta per verificare che essi sono in realtà sullo stesso dispositivo)
Per il secondo punto, utilizzare os.statvfs
per ottenere dimensione del blocco e informazioni di utilizzo.
(Disclaimer: Ho testato niente di tutto questo, la maggior parte di quello che so è venuto dalle fonti coreutils)
Per la seconda parte della tua domanda, "ottenere statistiche di utilizzo della partizione dato", psutil rende questo facile con la href="https://psutil.readthedocs.io/en/latest/#psutil.disk_usage" rel="nofollow noreferrer"> disk_usage (percorso) funzione
semplice esempio dalla documentazione:
>>> import psutil
>>> psutil.disk_usage('/')
sdiskusage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)
psutil funziona con le versioni di Python da 2.6 a 3.6 e su Linux, Windows e OSX tra le altre piattaforme.
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')
Di solito la directory /proc
contiene tali informazioni in Linux, è un filesystem virtuale. Ad esempio, /proc/mounts
fornisce informazioni sulle attuali dischi montati; ed è possibile analizzare direttamente. Utilità come top
, df
tutti fanno uso di /proc
.
Non ho usato, ma questo potrebbe aiutare anche, se si vuole un wrapper: http : //bitbucket.org/chrismiles/psi/wiki/Home