[Tutor] Filesystem Usage

Kent Johnson kent37 at tds.net
Fri Jan 19 15:55:44 CET 2007


Steve Nelson wrote:
> On 9/22/06, Steve Nelson <sanelson at gmail.com> wrote:
> 
>> In the end I just did:
>>
>> def fsUsage(dir):
>>   """Returns the % usage of a given filesystem"""
>>   stat = os.statvfs(dir)
>>   from statvfs import F_BLOCKS, F_BFREE
>>   total = stat[F_BLOCKS]
>>   avail = stat[F_BFREE]
>>   used = total-avail
>>   percent = used/total*100
>>   return percent
> 
> Can someone explain how I manged to import F_BLOCKS and F_BFREE?

With the statement
   from statvfs import F_BLOCKS, F_BFREE
> 
> I want to do the same with pwd and grp:
> 
>>>> gstat = grp.getgrgid(1)
>>>> dir(gstat)
> ['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
> '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__',
> '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__',
> '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
> '__repr__', '__rmul__', '__setattr__', '__str__', 'gr_gid', 'gr_mem',
> 'gr_name', 'gr_passwd', 'n_fields', 'n_sequence_fields',
> 'n_unnamed_fields']
> 
>>>> gstat[0]
> 'staff'
>>>> gstat[GR_GID]
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> NameError: name 'GR_GID' is not defined

Try gstat.gr_gid, etc
> 
> What's the difference?

F_BLOCKS is an attribute of the statvfs module; it is a constant giving 
the offset into the stats structure.

gr_gid is an attribute of the gstat object, it is the actual value that 
you want.

The objects returned by statvfs and getgrgid are unusual in that their 
attributes can be accessed in two ways, as list values and as object 
attributes.

The list-like access uses brackets [] and an index. In the case of 
statvfs, the constants are named in the statvfs module; in the case of 
getgrgid() there don't seem to be symbolic names available.

The attribute access uses . notation and an attribute name. You can do 
stat.f_blocks and gstat.gr_gid. Python takes care of looking up the 
actual attribute value.

I suggest you use the attribute form for both, it is more compact and 
readable, consistent between both types of objects, and doesn't require 
the import of statvfs.

Kent



More information about the Tutor mailing list