Is there any way to unimport a library

DevPlayer devplayer at gmail.com
Wed Nov 23 22:09:49 EST 2011


Seems so far the common way to fully unload any import is to exit the
Python session.
Only if this is true do I offer this hackish idea:

Therefore you might wish to run an os script instead of a python
script right off.
Here is my hack at it... Something like this:

file myapp.bat
--------------
python get_availble_imports.py available_imports.log
python myapp.py available_imports.log


file get_availble_imports.py
----------------------------
find_module_names = """
os sys time
sqlite lib1_verA lib2_verA
sqlite3 lib1_verB lib2_verB
"""

# other code i'm leaving out of this forum post

def find_module_names_using_pydoc( block_string ):

    '''Searchs for module names, provided in a block string,
    against the resultant module names list returned from pydoc. \n
    Returns a list of strings, being the intersection of module names
    from both lists.'''

    all_wanted_modules = parse_block_for_module_names( block_string )
# use split and drop empties

    module_names_found = []

    # walk_packages actually imports libraries;
    # so you know the import should work.
    # i call em modules; but they could be packages too

    # following line can take many seconds to run
    package_generator = pydoc.pkgutil.walk_packages(path=None,
prefix='', onerror=error_handler)

    for package_name in package_generator:
        module_loader, module_name, ispkg = package_name
        if module_name in all_wanted_modules:
            module_names_found.append( module_name )
            print repr( module_name )

    return module_names_found

found = find_module_names_using_pydoc( find_module_names )

#Then with a switch statement (if/elif) create a string with to be
#saved to the log file with what module names are in usable_mods

if 'sqlite' in found and 'lib1_verA' in found and 'lib2_verA' in
found:
    save('import sqlite, lib1_verA, lib2_verA')
elif 'sqlite' in found and 'lib1_verB' in found and 'lib2_verB' in
found:
    save('import sqlite3, lib1_verB, lib2_verB')
else:
    raise ImportError('Necessary packages not found')


file myapp.py
-------------
with open('available_imports.log','r') as f:
    text = f.read()
exec(text)
# DONE



More information about the Python-list mailing list