Find free disk space in python on OS/X

后端 未结 7 1149
死守一世寂寞
死守一世寂寞 2020-12-08 07:51

I\'m looking for the number of free bytes on my HD, but have trouble doing so on python.

I\'ve tried the following:

import os

stat = os.statvfs(path         


        
7条回答
  •  离开以前
    2020-12-08 08:23

    It's not OS-independent, but this works on Linux, and probably on OS X as well:

    print commands.getoutput('df .').split('\n')[1].split()[3]

    How does it work? It gets the output of the 'df .' command, which gives you disk information about the partition of which the current directory is a part, splits it into two lines (just as it is printed to the screen), then takes the second line of that (by appending [1] after the first split()), then splits that line into different whitespace-separated pieces, and, finally, gives you the 4th element in that list.

    >>> commands.getoutput('df .')
    'Filesystem           1K-blocks      Used Available Use% Mounted on\n/dev/sda3             80416836  61324872  15039168  81% /'
    
    >>> commands.getoutput('df .').split('\n')
    ['Filesystem           1K-blocks      Used Available Use% Mounted on', '/dev/sda3             80416836  61324908  15039132  81% /']
    
    >>> commands.getoutput('df .').split('\n')[1]
    '/dev/sda3             80416836  61324908  15039132  81% /'
    
    >>> commands.getoutput('df .').split('\n')[1].split()
    ['/dev/sda3', '80416836', '61324912', '15039128', '81%', '/']
    
    >>> commands.getoutput('df .').split('\n')[1].split()[3]
    '15039128'
    
    >>> print commands.getoutput('df .').split('\n')[1].split()[3]
    15039128
    

提交回复
热议问题