[Tutor] .strip question

Peter Otten __peter__ at web.de
Wed Jan 9 20:01:35 CET 2013


richard kappler wrote:

> I have a sort of a dictionary resulting from psutil.disk_usage('/') that
> tells me info about my hard drive, specifically:
> 
> usage(total=147491323904, used=62555189248, free=77443956736,
> percent=42.4)
> 
> I'm having a bit of a brain fudge here and can't remember how to strip out
> what I want. All I want to end up with is the number percent (in this case
> 42.4)  I started playing with .strip but the usage term before the parens
> gets in the way. If it weren't for that I could convert this into a dict
> and just pull the number by the key, right? So how do I strip out the
> 'usage' string? Once I do that, I think I know what I'm doing but here's
> my proposed code to look at if you would.
> 
> import psutil as ps
> 
> disk = ps.disk_usage('/')
> 
> # whatever I need to do to strip usage out
> 
> d = {}
> for item in disk.split(','):
>     item = item.strip()
>     key, value = item.split(':')
>     key = key.strip()
>     value = value.strip()
>     d[key] = float(value)
> return d
> 
> Mind you, this is as of yet untested code, so before you ask for
> tracebacks, I can't give any until I figure out how to get rid of the
> preceding 'usage'.

Problems like this are easily attacked in the interactive interpreter. With 
dir() you can find out an object's attributes:

>>> import psutil
>>> du = psutil.disk_usage("/")
>>> du
usage(total=244020019200, used=72860221440, free=158764216320, percent=29.9)
>>> dir(du)
['__add__', '__class__', '__contains__', '__delattr__', '__dict__', 
'__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', 
'__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', 
'__init__', '__iter__', '__le__', '__len__', '__lt__', '__module__', 
'__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', 
'__rmul__', '__setattr__', '__sizeof__', '__slots__', '__str__', 
'__subclasshook__', '_asdict', '_fields', '_make', '_replace', 'count', 
'free', 'index', 'percent', 'total', 'used']

As you can see one of du's attributes is percent, so let's have a look at 
its contents:

>>> du.percent
29.9

So that was easy, wasn't it? No need for string manipulation.



More information about the Tutor mailing list