convert attributes of an object to a string in python -


i have list of of objects defined

class track(object):   def __init__(self, title, artist, album, source, dest):     self.title = title     self.artist = artist     self.album = album     self.source = source     self.dest = dest 

on gui have button tied event. output supposed print contents of list command line (not gui)

def onprintbtn(self, event):     print "onprintbtn"      track in self.trackolv:        print(track) 

for reason ended in infinite loop of (class 'main.track')

i understand problem attributes part of object, don't know how convert them string values can print them out needed.

per request here entire code program.

#boa:frame:frame1  import wx import os import glob import shutil import datetime mutagen.mp3 import mp3 mutagen.easyid3 import easyid3 import mutagen.id3 import unicodedata  objectlistview import objectlistview, columndefn    ######################################################################## class track(object):     def __init__(self, title, artist, album, source, dest):         self.title = title         self.artist = artist         self.album = album         self.source = source         self.dest = dest      def __str__(self):         return "'%s' %s on teh ablum '%s'\nsource: %s\ndest: %s" % \             (self.title, self.artist, self.album, self.source, self.dest)      def __unicode__(self):         return unicode(str(self))  class action(object):     def __init__(self, timestamp, action, result):         self.timestamp = timestamp         self.action = action         self.result = result  ######################################################################## # non gui ########################################################################  def selectfolder(smessage):     print "select folder"     dlg = wx.dirdialog(none, message = smessage)      if dlg.showmodal() == wx.id_ok:         # user has selected something, path, set window's title path         filename = dlg.getpath()        else:         filename = "none selected"      dlg.destroy()     return filename   def getlist(sourcedir):     print "getlist"     listoffiles = none     print "-list set none"      listoffiles = glob.glob(sourcedir + '/*.mp3')      return listoffiles  def getlistrecursive(sourcedir):     print "getlistrecursive"     listoffiles = none     listoffiles = []     print "-list set none"      root, dirs, files in os.walk(sourcedir):         file in files:             if file.endswith(".mp3"):                 listoffiles.append(os.path.join(root,file))      #print listoffiles      return listoffiles  def strip_accents(s):     print "strip_accents"     return ''.join((c c in unicodedata.normalize('nfd', s) if unicodedata.category(c) != 'mn'))     def replace_all(text):     print "replace_all " + text     dictionary = {'\\':"", '?':"", '/':"", '...':"", ':':"", '&':"and"}      print text     print text.decode('utf-8')      text = strip_accents(text.decode('utf-8'))      i, j in dictionary.iteritems():         text = text.replace(i,j)      return text  def gettitle(filename):     print "gettitle"     audio = mp3(filename)      try:         stitle = str(audio["tit2"])     except keyerror:         stitle = os.path.basename(filename)         frame.lvactions.append([datetime.datetime.now(),filename,"title tag not exist, set filename"])      # todo: offer set title filename     ## if filename != filename     ##  prompt user action     ##  offer y/n/a      stitle = replace_all(stitle)      return stitle  def getartist(filename):     print "get artist"      audio = mp3(filename)      try:         sartist = str(audio["tpe1"])     except keyerror:         sartist = "unkown"         frame.lvactions.append([datetime.datetime.now(),filename,"artist tag not exist, set unkown"])      #replace special chars cause dir path errors     sartist = replace_all(sartist)      #if name = 'the beatles' change 'beatles, the'     if sartist.lower().find('the') == 0:         sartist = sartist.replace('the ',"")         sartist = sartist.replace('the ',"")         sartist = sartist + ", the"      return sartist  def getablum(filename):     print "get album"     audio = mp3(filename)      try:         salbum = str(audio["talb"])     except keyerror:         salbum = "unkown"         frame.lvactions.append([datetime.datetime.now(),filename,"album tag not exist, set unkown"])      #replace special chars cause dir path error         salbum = replace_all(salbum)     return salbum   ######################################################################## # gui ######################################################################## class mainpanel(wx.panel):     #----------------------------------------------------------------------     def __init__(self, parent):         wx.panel.__init__(self, parent=parent, id=wx.id_any)          self.trackolv = objectlistview(self, wx.id_any,                                        style=wx.lc_report|wx.sunken_border)         self.settracks()           # allow cell values edited when double-clicked         self.trackolv.celleditmode = objectlistview.celledit_singleclick          self.actionsolv = objectlistview(self, wx.id_any,                                          style=wx.lc_report|wx.sunken_border)         self.setactions()                   # create browse source button         sourcebtn = wx.button(self, wx.id_any, "browse source")         sourcebtn.bind(wx.evt_button, self.onbrowsesource)                  # create source txt box         self.txsource = wx.textctrl(self, wx.id_any, name=u'txsource', value=u'')          # create browse dest button         destbtn = wx.button(self, wx.id_any, "browse destination")         destbtn.bind(wx.evt_button, self.onbrowsedest)          # create dest txt box          self.txdest = wx.textctrl(self, wx.id_any, name=u'txdest', value=u'')                   # create move files button         movebtn = wx.button(self, wx.id_any, "move files")         movebtn.bind(wx.evt_button, self.onmovefiles)          # print list button - debug         printbtn = wx.button(self, wx.id_any, "print list")         printbtn.bind(wx.evt_button, self.onprintbtn)          # create check box include sub files         self.cbsubfolders = wx.checkbox(self, wx.id_any,               label=u'include subfolders', name=u'cbsubfolders', style=0)         self.cbsubfolders.setvalue(true)         self.cbsubfolders.bind(wx.evt_checkbox, self.oncbsubfolderscheckbox)          # create check box repace file names         self.cbreplacefilename = wx.checkbox(self, wx.id_any,               label=u'replace filename title tag',               name=u'cbreplacefilename', style=0)         self.cbreplacefilename.setvalue(false)         self.cbreplacefilename.bind(wx.evt_checkbox, self.oncbreplacefilenamecheckbox)          # create sizers         mainsizer = wx.boxsizer(wx.vertical)         feedbacksizer = wx.boxsizer(wx.vertical)         sourcesizer = wx.boxsizer(wx.horizontal)         btnsizer = wx.boxsizer(wx.horizontal)           feedbacksizer.add(self.trackolv, 1, wx.all|wx.expand, 2)         feedbacksizer.add(self.actionsolv, 1, wx.all|wx.expand, 2)          sourcesizer.add(sourcebtn, 0, wx.all, 2)         sourcesizer.add(self.txsource, 1, wx.all|wx.expand, 2)          sourcesizer.add(destbtn, 0, wx.all, 2)         sourcesizer.add(self.txdest, 1, wx.all|wx.expand, 2)          btnsizer.add(printbtn)         btnsizer.add(movebtn, 0, wx.all, 2)         btnsizer.add(self.cbsubfolders, 0, wx.all, 2)         btnsizer.add(self.cbreplacefilename, 0, wx.all, 2)          mainsizer.add(feedbacksizer, 1 , wx.all|wx.expand, 2)         mainsizer.add(sourcesizer, 0, wx.all|wx.expand, 2)         #mainsizer.add(destsizer, 0, wx.all|wx.expand, 2)         #mainsizer.add(destsizer, 0, wx.all|wx.expand, 2)         mainsizer.add(btnsizer, 0, wx.all, 2)         self.setsizer(mainsizer)         mainsizer.fit(self)      #----------------------------------------------------------------------     # set gui column headers , width     #----------------------------------------------------------------------     def settracks(self, data=none):         self.trackolv.setcolumns([             columndefn("title", "left", 100, "title"),             columndefn("artist", "left", 100, "artist"),             columndefn("album", "left", 100, "album"),             columndefn("source", "left", 300, "source"),             columndefn("destination", "left", 300, "dest"),         ])       def setactions(self, data=none):         self.actionsolv.setcolumns([             columndefn("time", "left", 100, "timestamp"),             columndefn("action", "left", 450, "action"),             columndefn("result", "left", 450, "result")         ])      #----------------------------------------------------------------------     # gui events     #-----------------------------------------------------------------------     eventlist = [action]      #select source of files     def onbrowsesource(self, event):         print "onbrowsesource"             source = selectfolder("select source directory")          print source          self.txsource.setvalue(source)         self.anevent = [action(datetime.datetime.now(),source,"set source dir")]         self.actionsolv.addobjects(self.anevent)          self.populatelist()      #select source of files     def onbrowsedest(self, event):         print "onbrowsedest"             dest = selectfolder("select destination directory")          print dest          self.txdest.setvalue(dest)         self.anevent = [action(datetime.datetime.now(),dest,"set destination dir")]         self.actionsolv.addobjects(self.anevent)          self.populatelist()      def oncbsubfolderscheckbox(self, event):         print "cbsubfolder"         self.populatelist()             def oncbreplacefilenamecheckbox(self, event):         print "cbreplacefilename"         self.populatelist()      def onmovefiles(self, event):         print "onmovefiles"         self.movefiles()      def onprintbtn(self, event):         print "onprintbtn"          track in self.trackolv:             print (track)     #-------------     #computations     #-------------      def definedestfilename(self, sfulldestpath):         print "define dest"          icopyx = 0         bexists = false         sorigname = sfulldestpath          #if file not exist return original path/filename         if os.path.isfile(sfulldestpath) == false:             print "-" + sfulldestpath + " valid"             return sfulldestpath          #add .copyx.mp3 end of file , retest until new filename found         while bexists == false:             sfulldestpath = sorigname             icopyx += 1             sfulldestpath = sfulldestpath + ".copy" + str(icopyx) + ".mp3"             if os.path.isfile(sfulldestpath) == false:                 print "-" + sfulldestpath + " valid"                 self.lvactions.append([datetime.datetime.now(),"desitnation filename changed since file exists",sfulldestpath])                 bexists = true          #return path/filename.copyx.mp3         return sfulldestpath       def populatelist(self):         print "populatelist"          ssource = self.txsource.value         sdest = self.txdest.value          #initalize list reset values on option change         self.initiallist = [track]         self.trackolv.setobjects(self.initiallist)          #create list of files         if self.cbsubfolders.value == true:             listoffiles = getlistrecursive(ssource)         else:             listoffiles = getlist(ssource)              print listoffiles          #prompt if no files detected         if listoffiles == []:             self.anevent = [action(datetime.datetime.now(),"parse source .mp3 files","no .mp3 files in source directory")]             self.actionsolv.addobjects(self.anevent)          #populate list after both source , dest chosen         if len(sdest) > 1 , len(sdest) > 1:                  print "-iterate listoffiles"              file in listoffiles:                  (ssource,sfilename) = os.path.split(file)                  print ssource                 print sfilename                  #sfilename = os.path.basename(file)                 stitle = gettitle(file)                 try:                     sartist = getartist(file)                 except unicodedecodeerror:                     print "unicode"                     sartist = "unkown"                  salbum = getablum(file)                  # make path = sdest + artist + album                 sdestdir = os.path.join (sdest, sartist)                 sdestdir = os.path.join (sdestdir, salbum)                   #if file exists change destination *.copyx.mp3                 if self.cbreplacefilename.value == true:                     sdestdir = self.definedestfilename(os.path.join(sdestdir,stitle))                 else:                     sdestdir = self.definedestfilename(os.path.join(sdestdir,sfilename))                  # populate listview drive contents                  #ssource = self.txsource.value                 sdest = self.txdest.value                  # todo: make source = exact source of track, not parent source                 # todo: seperate dest , filename                 self.atrack = [track(stitle,sartist,salbum,ssource, sdestdir)]                 self.trackolv.addobjects(self.atrack)                 self.update()                   #populate list later use in move command                 #self.validatedmove.append([file,sdestdir])                 print "-item added sourcedest list"         else:             print "-list not iterated"      def movefiles (self):         print "move files"          #for track in self.trackolv:         #    print "-iterate sourcedest"         #    #create dir         #    (sdest,filename) = os.path.split(self.trackolv)         #    print "-check dest"         #             #    if not os.path.exists(sdest):         #        print "-created dest"         #        os.makedirs(sdest)         #        self.lvactions.append([datetime.datetime.now(),sdest,"created"])         #        self.update()         #        self.lvactions.ensurevisible(self.lvactions.getitemcount() -1)         #         #    #move file         #    print "-move file"         #    shutil.move(sourcedest[0],sourcedest[1])         #    self.lvactions.append([datetime.datetime.now(),filename,"moved"])         #    self.update()         #    self.lvactions.ensurevisible(self.lvactions.getitemcount() -1)         #         #self.lvactions.append([datetime.datetime.now(),"move complete","success"])         #self.update()         #self.lvactions.ensurevisible(self.lvactions.getitemcount() -1)        ######################################################################## class mainframe(wx.frame):     #----------------------------------------------------------------------     def __init__(self):         wx.frame.__init__(self, parent=none, id=wx.id_any,                           title="mp3 manager", size=(1024,768)) #w h         panel = mainpanel(self)  ######################################################################## class genapp(wx.app):      #----------------------------------------------------------------------     def __init__(self, redirect=false, filename=none):         wx.app.__init__(self, redirect, filename)      #----------------------------------------------------------------------     def oninit(self):         # create frame here         frame = mainframe()         frame.show()         return true  #---------------------------------------------------------------------- def main():     """     run demo     """     app = genapp()     app.mainloop()  if __name__ == "__main__":     main() 

you'll want override __str__ and/or __unicode__ special methods custom class.

class track(object):     ...     def __str__(self):         return "'%s' %s on album '%s'\nsource: %s\ndest: %s" % \             (self.title, self.artist, self.album, self.source, self.dest)     def __unicode__(self):         return unicode(str(self)) 

then time try print or string format instance of object, appropriate method called


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -