[Tutor] String Encoding problem

Strax-Haber, Matthew (LARC-D320) matthew.strax-haber at nasa.gov
Mon Apr 20 23:17:07 CEST 2009


Sorry about that. Hopefully this is better:
In operator:
def __init__(self, path, saveDB=True, cleanUp=True):
    '''Constructor'''
    ## Calculate filesystem paths
    self.WORK_DIR    = path + '.tmp'
    DB_PATH        = path + '.xml'
    self.SAVE_DB    = saveDB    ## finish(): Delete unnecessary files created by run?
    self.CLEANUP    = cleanUp    ## finish(): Delete database at end of run?

    ## Make sure we have a working directory (exception on failed write)
    if not os.path.isdir(self.WORK_DIR):
        os.mkdir(self.WORK_DIR)

        self._db             = DB.Database(DB_PATH)
        ## SOME OTHER ENVIRONMENT SETUP STUFF

def _cleanUpEnvironment(self):
    '''Delete temp files created for this run'''
    try:
        for path,dirs,files in os.walk(self.WORK_DIR, topdown=False):
            for f in files:    os.unlink(os.path.join(path,f))
            for d in dirs:    os.rmdir(os.path.join(path,d))
        os.rmdir(self.WORK_DIR)
    except:
        print >>sys.stderr, 'Could not delete temp files; left at:'
        print >>sys.stderr, self.WORK_DIR

def finish(self):
    '''Clean up and finish the run (write out to the database)'''
    if self.SAVE_DB:    self._db.commit()
    if self.CLEANUP:    self._cleanUpEnvironment()

def __del__(self):
    ## FIXME: Known bug:
    ##  del t at command line works properly
    ##  Ctrl-D, when there is no db file present, results in a LookupError
    self.finish()

if __name__ == '__main__':
    printHelp()
    ## Provide tab completion to the user
    import readline, rlcompleter
    readline.parse_and_bind('tab: complete')
    t    = OperatorClassName(os.path.splitext(__file__)[0])


In database:
def __init__(self, path):
    '''Constructor'''
    self.__dbpath = path    ## Path to the database
    self.load()

def load(self):
    '''Read the database out from the file'''
    from xml.parsers.expat import ExpatError

    if os.path.exists(self.__dbpath):
        ## Noticed exceptions: IOError, ExpatError
        try:
            self.root = ET.parse(self.__dbpath).getroot()
        except ExpatError:
            raise ExpatError('Invalid XML in ' + self.__dbpath)
    else:
        self.root = ET.Element("root")

def commit(self):
    '''Write the database back to the file'''
    ## Noticed exceptions: IOError
    ET.ElementTree(self.root).write(self.__dbpath)
--
~Matthew Strax-Haber
National Aeronautics and Space Administration
Langley Research Center (LaRC)
Co-op, Safety-Critical Avionics Systems Branch
W: 757-864-7378; C: 561-704-0029
Mail Stop 130
Matthew.Strax-Haber at nasa.gov


________________________________
From: Martin Walsh <mwalsh at mwalsh.org>
Date: Mon, 20 Apr 2009 16:05:01 -0500
To: Python Tutor <tutor at python.org>
Cc: "Strax-Haber, Matthew (LARC-D320)" <matthew.strax-haber at nasa.gov>
Subject: Re: [Tutor] String Encoding problem

Forwarding to the list. Matt, perhaps you can repost in plain text, my
mail client seems to have mangled your source ...

Strax-Haber, Matthew (LARC-D320) wrote:
>> *From: *Martin Walsh <mwalsh at mwalsh.org>
>>
>> The environment available to __del__ methods during program termination
>> is wonky, and apparently not very consistent either. I can't say that I
>> completely understand it myself, perhaps someone else can provide a
>> better explanation for both of us, but some of the causes are described
>> in the documentation:
>>
>> http://docs.python.org/reference/datamodel.html#object.__del__
>>
>> What is your rationale for using __del__? Are you trying to force a
>> 'commit()' call on Database instances when your program terminates -- in
>> the case of an unhandled exception, for example?
>
> Perhaps I oversimplified a bit. In my actual code, there is a database
> class and an operator class. The actual structure is this:
>
> In operator:
>     def __init__(self, path, saveDB=True, cleanUp=True):
>        '''Constructor'''        ## Calculate filesystem paths
>        self.WORK_DIR    = path + '.tmp'        DB_PATH            = path
> + '.xml'        self.SAVE_DB    = saveDB    ## finish(): Delete
> unnecessary files created by run?        self.CLEANUP    = cleanUp    ##
> finish(): Delete database at end of run?                ## Make sure we
> have a working directory (exception on failed write)        if not
> os.path.isdir(self.WORK_DIR):            os.mkdir(self.WORK_DIR)
>
>        self._db             = DB.Database(DB_PATH)
>         ## SOME OTHER ENVIRONMENT SETUP STUFF
>     def _cleanUpEnvironment(self):          try:            ## Delete
> temp files created for this run            for path,dirs,files in
> os.walk(self.WORK_DIR, topdown=False):                for f in files:
>    os.unlink(os.path.join(path,f))                for d in dirs:
>    os.rmdir(os.path.join(path,d))            os.rmdir(self.WORK_DIR)
>        except:            print >>sys.stderr, 'Could not delete temp
> files; left at:'            print >>sys.stderr, self.WORK_DIR    def
> finish(self):            '''Clean up and finish the run (write out to
> the database)'''            if self.SAVE_DB:        self._db.commit()
>            if self.CLEANUP:        self._cleanUpEnvironment()
>     def __del__(self):        ## FIXME: Known bug:        ##  del t at
> command line works properly        ##  Ctrl-D, when there is no db file
> present, results in a LookupError        self.finish()
> if __name__ == '__main__':
>     printHelp()
>     ## Provide tab completion to the user    import readline,
> rlcompleter    readline.parse_and_bind('tab: complete')
>     t    = OperatorClassName(os.path.splitext(__file__)[0])
>
> In database:
>     def commit(self):        '''Write the database back to the file'''
>        ## Noticed exceptions: IOError
>        ET.ElementTree(self.root).write(self.__dbpath)
>
> The operator also has a series of functions that collect data and enter
> it into the database. Here's the usage pattern I want to have:
>
> User calls Operator.py. User runs a bunch of functions of the form
> t.<someFunc>(<args>). When the user quits, the database will save or not
> save depending on the status of t.SAVE_DB (which some functions in the
> operator will programmatically change).
>
>>
>> HTH,
>> Marty
>>
>>>
>>> Thank you very much. Any and all help or pointers are appreciated.
>>>
>>> ~Matt
>>>
>>> #### db.py ###
>>> from xml.etree import ElementTree as ET
>>> import os
>>>
>>> class Database(object):
>>>     def __init__(self, path):
>>>         self.__dbpath = path    ## Path to the database
>>>         self.load()
>>>     def __del__(self):
>>>         ## FIXME: Known bug:
>>>         ##  del db at command line works properly
>>>         ##  Ctrl-D, when there is no db file present, results in a
>>> LookupError
>>>         ##    and empty xml file
>>>         from StringIO import StringIO
>>>         from traceback import print_exc
>>>         trace = StringIO()
>>>         try:
>>>             print 5
>>>             self.commit()
>>>             print 7
>>>         except Exception:
>>>             print_exc(100, trace)
>>>             print trace.getvalue()
>>>     def load(self):
>>>         if os.path.exists(self.__dbpath):
>>>             self.root = ET.parse(self.__dbpath).getroot()
>>>         else:
>>>             self.root = ET.Element("root")
>>>     def commit(self):
>>>         ET.ElementTree(self.root).write(self.__dbpath)
>>> db = Database('db.xml')
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>
> --
> ~Matthew Strax-Haber
> National Aeronautics and Space Administration
> Langley Research Center (LaRC)
> Co-op, Safety-Critical Avionics Systems Branch
> W: 757-864-7378; C: 561-704-0029
> Mail Stop 130
> Matthew.Strax-Haber at nasa.gov


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090420/eb010924/attachment-0001.htm>


More information about the Tutor mailing list