Created
April 10, 2014 05:52
-
-
Save rebx/10346049 to your computer and use it in GitHub Desktop.
whichpy -- a nifty script for finding where your python module is imported from
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import sys | |
from os.path import basename, dirname | |
from re import compile as regxcomp | |
from re import match as regxmat | |
INIT_BNAME = regxcomp('__init__.py') | |
def try_import(module_name): | |
try: | |
exec("import " + module_name + " as mod_name_loaded") | |
except ValueError, SyntaxError: | |
print "Please give a module name to check" | |
return False | |
except ImportError: | |
print "No module named %s" % (module_name) | |
return False | |
except: | |
print "Unhandled exception: ", sys.exc_info()[0] | |
return False | |
module_name_loc = mod_name_loaded.__file__ | |
if regxmat(INIT_BNAME, basename(module_name_loc)): | |
module_name_loc = dirname(module_name_loc) | |
print "Module: %s is located at %s" % (module_name, module_name_loc) | |
return True | |
def main(module_name): | |
if module_name is None: | |
print "Please give a module name to check" | |
return False | |
return try_import(module_name) | |
if __name__ == '__main__': | |
if main(sys.argv[-1]) is True: | |
sys.exit(0) | |
sys.exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment