How does one do the equivalent of “import * from module” with Python's __import__ function?

前端 未结 5 761
温柔的废话
温柔的废话 2020-11-29 03:51

Given a string with a module name, how do you import everything in the module as if you had called:

from module import *

i.e. given string

5条回答
  •  庸人自扰
    2020-11-29 04:34

    Here's my solution for dynamic naming of local settings files for Django. Note the addition below of a check to not include attributes containing '__' from the imported file. The __name__ global was being overwritten with the module name of the local settings file, which caused setup_environ(), used in manage.py, to have problems.

    try:
        import socket
        HOSTNAME = socket.gethostname().replace('.','_')
        # See http://docs.python.org/library/functions.html#__import__
        m = __import__(name="settings_%s" % HOSTNAME, globals=globals(), locals=locals(), fromlist="*")
        try:
            attrlist = m.__all__
        except AttributeError:
            attrlist = dir(m)        
        for attr in [a for a in attrlist if '__' not in a]:
            globals()[attr] = getattr(m, attr)
    
    except ImportError, e:
        sys.stderr.write('Unable to read settings_%s.py\n' % HOSTNAME)
        sys.exit(1)
    

提交回复
热议问题