Possible modification to file_open class (define in Util)

class file_open:
    """open a file using default path.  The default file path may be
    set on initialization and changed any time later.
    This class is intended to override the builtin function open
    The equivalent operation file is used here to return a file
    object.  Note do not override the builtin function 'file' with this class
    or you'll enter an infinite loop!!!  
     * two cases for finding the file:
     1. fname has full path (or rel path to cwd), or file is in cwd
        -> dont use file_path
     2. fname has rel path (or none) to default path
        -> join file_path and fname
    """
    def __init__(self,file_path=''):
        self.file_path=file_path
    def __call__(self,*args,**kw):
        if len(args) > 0:
            fname = args[0]
            args = args[1:]
        else:
            raise IOError, "No file name given"

        if os.path.isfile(fname):
            #return open(fname)
            return file(fname,*args,**kw)
        elif self.file_path:
            fname = os.path.join(self.file_path,fname)
            #return open(fname)
            return file(fname,*args,**kw)
        else:
            raise IOError, "Could not open file '%s'" % (fname)

  • To use this we should set (in shell.py or tdl.py)

    fpath = tdl.getVariableValue('_sys.work')
    if fpath == None:
        fpath = tdl.getVariableValue('_sys.home')
    if fpath == None:
        fpath = ''
    __builtins__['open'] = Util.file_open(file_path=fpath)
  • Then define a new _sys.set_file_path function:

def set_work_path(file_path='',tdl=None):
    if hasattr(open,'file_path'):
        open.file_path = file_path
    print "Default file path = %s" % open.file_path
    tdl.setVariable('_sys.work',file_path)
    return
  • Then at tdl prompt the following should work:

tdl>>_sys.set_work_path _sys.home + /data

tdl>>_sys.set_work_path /usr/bob


FileOpen (last edited 2006-06-25 22:13:39 by TomTrainor)