Skip to content

Instantly share code, notes, and snippets.

@christophercrouzet
Created August 5, 2014 13:18
Show Gist options
  • Save christophercrouzet/3a12f676b2b709f6b23c to your computer and use it in GitHub Desktop.
Save christophercrouzet/3a12f676b2b709f6b23c to your computer and use it in GitHub Desktop.
Retrieves a module name from a path
import inspect
import os
def get_module_name_from_path(path):
if not os.path.exists(path):
raise ValueError("The path '%s' is not a valid path." % path)
path = os.path.abspath(path)
full_names = []
for sys_path in sys.path:
if path.startswith(sys_path):
relative_path = path[len(sys_path):].lstrip(os.sep)
if not relative_path:
continue
full_name_parts = relative_path.split(os.sep)
module_name = inspect.getmodulename(path)
if module_name:
if module_name == '__init__':
del full_name_parts[-1]
else:
full_name_parts[-1] = module_name
elif os.path.isfile(path):
raise ValueError("The path '%s' is not a valid module." % path)
if full_name_parts:
full_names.append('.'.join(full_name_parts))
full_names.sort(key=lambda full_name: -len(full_name))
for full_name in full_names:
if full_name in sys.modules:
return full_name
return full_names[0] if full_names else None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment