How to find “import name” of any package in Python?

后端 未结 3 1290
孤街浪徒
孤街浪徒 2020-12-06 05:31

I wonder if is there any reliable and consistant way to get a Python package\'s \"import name\" / namespace. For example;

Package; django-haystack

3条回答
  •  离开以前
    2020-12-06 06:02

    In principal, everything you need to get that information is in the setup.py that is supposed to be in every such package. That information would roughly be the union of the packages, py_modules, ext_package and ext_modules of the Distribution object. In fact, here's a little script that mocks out distutils.core.setup just for the purpose of getting that information.

    import distutils.core
    distutils.core._setup_stop_after = "config"
    _real_setup = distutils.core.setup
    def _fake_setup(*args, **kwargs):
        global dist
        dist = _real_setup(*args, **kwargs)
    
    distutils.core.setup = _fake_setup
    
    import sys
    setup_file = sys.argv[1]
    sys.argv[:] = sys.argv[1:]
    import os.path
    os.chdir(os.path.dirname(setup_file))
    
    execfile(os.path.basename(setup_file))
    
    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)]))
    
    print "\n".join(pkgs)
    

    For many packages, this will work like a charm, but for a counterexample, see numpy, It breaks because numpy provides its own distutils, and I can see no obvious way around it.

提交回复
热议问题