Skip to content

Instantly share code, notes, and snippets.

@kirpit
Created August 28, 2011 13:07
Show Gist options
  • Save kirpit/1176645 to your computer and use it in GitHub Desktop.
Save kirpit/1176645 to your computer and use it in GitHub Desktop.
Returns first level namespace (package import name) of a setuptools distribution
#! /usr/bin/env python2.7
'''
http://stackoverflow.com/questions/7184375/how-to-find-import-name-of-any-package-in-python
'''
import distutils.core
import sys
import os
def get_release_namespace(setup_file):
'''
Returns first level namespace (package import name)
of a setuptools distribution
'''
# setup wrapper
def _fake_setup(*args, **kwargs):
global dist
dist = _real['setup'](*args, **kwargs)
distutils.core._setup_stop_after = 'config'
# backup
_real = {
'argv': sys.argv,
'setup': distutils.core.setup,
'__file__': __file__,
'__path__': __path__,
'cwd': os.getcwd(),
}
# fake
sys.argv = [setup_file]
__file__ = setup_file
__path__ = os.path.dirname(__file__)
os.chdir(os.path.dirname(setup_file))
sys.path.append(__path__)
distutils.core.setup = _fake_setup
# run
execfile(os.path.basename(setup_file))
# get release info
cat = lambda *seq: sum((i for i in seq if i is not None), [])
pkgs = set(package.split('.')[0] for package
in cat(dist.packages,
dist.py_modules,
[m.name for m in cat(dist.ext_modules)],
[m.name for m in cat(dist.ext_package)]))
# restore
sys.argv = _real['argv']
distutils.core.setup = _real['setup']
os.chdir(_real['cwd'])
sys.path = sys.path[:-1]
# return only existing directories from "pkgs"
(package_dir, setup_py) = os.path.split(setup_file)
return [d for d in pkgs if d in os.listdir(package_dir)]
if __name__ == '__main__':
setup_file = sys.argv[1]
print get_release_namespace(setup_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment