#! /usr/bin/env python

"""
Find where the hell your Python stuff actually is.
"""

import sys, argparse


# Shamelessly taken from Werkzeug
# (c) 2010 by the Werkzeug Team
# BSD License
def import_string(import_name, silent=False):
    """Imports an object based on a string.  This is useful if you want to
    use import paths as endpoints or something similar.  An import path can
    be specified either in dotted notation (``xml.sax.saxutils.escape``)
    or with a colon as object delimiter (``xml.sax.saxutils:escape``).

    If `silent` is True the return value will be `None` if the import fails.

    :param import_name: the dotted name for the object to import.
    :param silent: if set to `True` import errors are ignored and
                   `None` is returned instead.
    :return: imported object
    """
    # force the import name to automatically convert to strings
    if isinstance(import_name, unicode):
        import_name = str(import_name)
    try:
        if ':' in import_name:
            module, obj = import_name.split(':', 1)
        elif '.' in import_name:
            module, obj = import_name.rsplit('.', 1)
        else:
            return __import__(import_name)
        # __import__ is not able to handle unicode strings in the fromlist
        # if the module is a package
        if isinstance(obj, unicode):
            obj = obj.encode('utf-8')
        try:
            mod = __import__(module, None, None, [obj])
            # whoopee
            getattr(mod, obj)
            return mod
        except (ImportError, AttributeError):
            # support importing modules not yet set up by the parent module
            # (or package for that matter)
            modname = module + '.' + obj
            __import__(modname)
            return sys.modules[modname]
    except ImportError:
        if not silent:
            raise


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('modules', nargs='+', metavar='importable',
        help='Anything that is importable')
    ns = parser.parse_args()
    success = True
    for name in ns.modules:
        mod = import_string(name, True)
        if mod is not None:
            path = mod.__file__
        else:
            success = False
            path = 'Not Found'
        print '%r: %s' % (name, path)
    if success:
        return 0
    else:
        return 1


if __name__ == '__main__':
    sys.exit(main())

