[Tutor] About UserDict class

steve lonetwin@yahoo.com
Wed, 4 Jul 2001 15:16:01 +0530


Greetings everyone,
 I'd like someone to explain this thing to me ....
I have a class mp3file (given below in entierty), which inherits from the=
=20
UserDict class, when I create a class instance from the intepreter window=
, it=20
initialises the tagdata (ie: reads the ID3 TAG and fills the dict with=20
key/value pairs)...funny thing is when I do the same from the command lin=
e=20
(create an object, associated with a file name passed as the argument) it=
=20
does not initialise the tagdata....
 I have no idea what's going wrong !!

Thanx & Peace
Steve

the code : (I've given the sample op after the code)
###############################################################
#!/usr/bin/python2.0

from UserDict import UserDict
import re=20
import curses=20
import os=20

def stripnulls(data):
    "strip whitespace and nulls"
    return data.replace("\0", " ").strip()

class mp3file(UserDict):
=09tagDataMap =3D { "title"   : (  3,  33, stripnulls)
=09=09=09"artist"  : ( 33,  63, stripnulls),
=09=09=09"album"   : ( 63,  93, stripnulls),
=09=09=09"year"    : ( 93,  97, stripnulls),
=09=09=09"comment" : ( 96, 126, stripnulls),
=09=09=09"genre"   : (127, 128, ord) }

=09rulez =3D { ('One or more underscores',              '_+'      ) : [ 1=
, ' '],
=09=09  ('Two or more hypens',                   '-{2,}'   ) : [ 1, '-'],
=09=09  ('An ampersand',                         '&'       ) : [ 1, 'And'=
],
=09=09  ('Words that have a hypen between them', '(-)(\w*)') : [ 1, r' \1=
 \2'] }

=09def __init__(self, flname =3D None):
=09=09UserDict.__init__(self)
=09=09self["old_name"] =3D flname
=09=09self["name"] =3D flname
=09
=09def __parse(self, flname):
=09=09try:
=09=09=09fl =3D open(flname, "rb", 0)
=09=09=09try:
=09=09=09=09fl.seek(-128, 2)
=09=09=09=09tagdata =3D fl.read()
=09=09=09finally:
=09=09=09=09fl.close()
=09=09=09if tagdata[:3] =3D=3D 'TAG':
=09=09=09=09for tag, (start, end, parseFunc) in self.tagDataMap.items():
=09=09=09=09=09self[tag] =3D parseFunc(tagdata[start:end])
=09=09except IOError:
=09=09=09pass
=09=09=09
=09=09
=09def __setitem__(self, key, item):
=09=09if key =3D=3D "name" and item:
=09=09=09self.__parse(item)
=09=09elif key in [ "title", "artist", "album", "comment" ]:
=09=09=09item =3D item[:30]=09=09# Truncate upto 30 chars
=09=09elif key =3D=3D "year":
=09=09=09item =3D item[:4]=09=09=09# Trancate upto 4 chars
=09=09UserDict.__setitem__(self, key, item)

=09def changeName(self):
=09=09for k in self.rulez.keys():
=09=09=09if self.rulez[k][0]:
=09=09=09=09self["name"] =3D re.sub(k[1], self.rulez[k][1], self["name"])
=09=09self["name"] =3D ' '.join([ x.capitalize() for x in self["name"].sp=
lit()])

=09def changeTag(self, tagdata):
=09=09for tag in tagdata.keys():
=09=09=09self[tag] =3D tagdata[tag]
=09
=09def writeTag(self):
=09=09try:
=09=09=09tag =3D 'TAG%-30s%-30s%-30s%-4s%-30s%s' % \
=09=09=09=09=09( self["title"], self["artist"], self["album"],
=09=09=09=09=09  self["year"], self["comment"], chr(self["genre"]))
=09=09=09try:
=09=09=09=09fl =3D open(self["name"], "rb")
=09=09=09=09p =3D fl.read()
=09=09=09=09fl.close()
=09=09=09=09p =3D p[:-128]+tag
=09=09=09=09fl =3D open(self["name"], "wb")
=09=09=09=09fl.write(p)
=09=09=09finally:
=09=09=09=09fl.close()
=09=09except IOError:
=09=09=09return 1
=09
if __name__ =3D=3D '__main__':
#=09print "Not yet ready ..."
=09initial_flist =3D os.sys.argv[1:] or os.listdir('./*.mp3')
=09names =3D []
=09for file in initial_flist:
=09=09dirnm =3D os.path.dirname(file)
=09=09fl =3D mp3file(os.path.basename(file))
=09=09print fl
=09=09raw_input()
##################################################
output :
##################################################
=09in the intepreter:

Python 2.1 (#3, Jun 25 2001, 13:39:27)=20
[GCC 2.95.3 19991030 (prerelease)] on linux2
Type "copyright", "credits" or "license" for more information.
>>> import foo
>>> fl =3D foo.mp3file('/home/steve/Mp3s/Eagles/Eagles - Full Album - Gre=
atest=20
Hits.mp3')
>>> print fl
{'artist': 'Eagles', 'genre': 0, 'old_name': '/home/steve/Mp3s/Eagles/Eag=
les=20
- Full Album - Greatest Hits.mp3', 'name': '/home/steve/Mp3s/Eagles/Eagle=
s -=20
Full Album - Greatest Hits.mp3', 'title': 'Greatest Hits', 'year': '',=20
'comment': '', 'album': 'Greatest Hits'}
>>>=20

=09on the prompt:
$ foo.py /home/steve/Mp3s/Eagles/Eagles - Full Album - Greatest Hits.mp3
{'old_name': 'Eagles', 'name': 'Eagles'}



=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=09
It is so very hard to be an
on-your-own-take-care-of-yourself-because-
there-is-no-one-else-to-do-it-for-you grown-up.
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D