Ignore:
Timestamp:
11/01/10 18:01:03 (3 years ago)
Author:
jdsiiro
Message:

Adding support for importing unexported symbols through import_file().
Also refining the import name parsing to explicitly look for .py or .pyc
extension, and raising an exception for '.' in the file name.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • pyutilib.misc/trunk/pyutilib/misc/import_file.py

    r1950 r2101  
    3030    This function returns the module object that is created. 
    3131    """ 
     32 
     33    # First thing to try: see if this is a module and not a file 
     34    module = None 
     35    try: 
     36        # is the module already imported? 
     37        module = sys.modules[filename] 
     38    except KeyError: 
     39        try: 
     40            module = __import__(filename) 
     41            #print "Imported module '%s'" % ( filename ) 
     42        except ImportError: 
     43            pass 
     44    if module is not None: 
     45        if not context is None: 
     46            context[name] = module 
     47        return module 
     48     
    3249    # 
    3350    # Parse the filename to get the name of the module to be imported 
    3451    # 
    3552    if '/' in filename: 
    36        tmp_import = (filename).split("/")[-1] 
     53        name = (filename).split("/")[-1] 
    3754    elif '\\' in filename: 
    38        tmp_import = (filename).split("\\")[-1] 
     55        name = (filename).split("\\")[-1] 
    3956    else: 
    40        tmp_import = filename 
    41     name = ".".join((tmp_import).split(".")[:-1]) 
     57        name = filename 
     58 
     59    # NB: endswith accepts tuples of strings starting in python 2.5. 
     60    # For 2.4 compatibility we will call endswith() twice. 
     61    if name.endswith('.py') or name.endswith('.pyc'): 
     62        name = name.rsplit('.', 1)[0] 
     63    if '.' in name: 
     64        raise RuntimeError, \ 
     65              "Invalid python module name=%s (contains '.')" % ( filename ) 
     66 
    4267    # 
    4368    # Get the module if it already exists, and otherwise 
     
    5075        sys.path.insert( 0, dirname ) 
    5176        try: 
    52            module = imp.load_source( name, filename ) 
     77            module = imp.load_source( name, filename ) 
     78            #print "Loaded module '%s'" % ( filename ) 
    5379        except: 
    5480           raise RuntimeError, "Failed to load python module="+str(filename) 
Note: See TracChangeset for help on using the changeset viewer.