简体   繁体   English

用Python的__import__函数如何等效于“从模块导入*”?

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

Given a string with a module name, how do you import everything in the module as if you had called: 给定一个带有模块名称的字符串,如何将模块中的所有内容导入,就像调用过的一样:

from module import *

ie given string S="module", how does one get the equivalent of the following: 即给定字符串S =“ module”,如何获得以下等价的内容:

__import__(S, fromlist="*")

This doesn't seem to perform as expected (as it doesn't import anything). 这似乎没有达到预期的效果(因为它没有导入任何东西)。

Please reconsider. 请重新考虑。 The only thing worse than import * is magic import * . 唯一比import *更糟糕的是magic import *

If you really want to: 如果您确实要:

m = __import__ (S)
try:
    attrlist = m.__all__
except AttributeError:
    attrlist = dir (m)
for attr in attrlist:
    globals()[attr] = getattr (m, attr)

Here's my solution for dynamic naming of local settings files for Django. 这是为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. 全局__name__被本地设置文件的模块名称覆盖,这导致在manage.py中使用的setup_environ()出现问题。

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)

It appears that you can also use dict.update() on module's dictionaries in your case: 看来您也可以在这种情况下对模块的字典使用dict.update()

config = [__import__(name) for name in names_list]

options = {}
for conf in config:
    options.update(conf.__dict__)

Update: I think there's a short "functional" version of it: 更新:我认为它有一个简短的“功能”版本:

options = reduce(dict.update, map(__import__, names_list))

The underlying problem is that I am developing some Django, but on more than one host (with colleagues), all with different settings. 潜在的问题是我正在开发一些Django,但是在多台主机(与同事)上使用不同的设置。 I was hoping to do something like this in the project/settings.py file: 我希望在project / settings.py文件中执行以下操作:

from platform import node

settings_files = { 'BMH.lan': 'settings_bmh.py", ... } 

__import__( settings_files[ node() ] )

It seemed a simple solution (thus elegant), but I would agree that it has a smell to it and the simplicity goes out the loop when you have to use logic like what John Millikin posted (thanks). 看来这是一个简单的解决方案(因此很优雅),但我同意它的味道,当您必须使用约翰·米利金(John Millikin)发表的逻辑(谢谢)时,这种简单性便会消失。 Here's essentially the solution I went with: 本质上是我使用的解决方案:

from platform import node

from settings_global import *

n = node()

if n == 'BMH.lan':
  from settings_bmh import *
# add your own, here...
else:
  raise Exception("No host settings for '%s'. See settings.py." % node())

Which works fine for our purposes. 对于我们的目的,哪个工作正常。

I didn't find a good way to do it so I took a simpler but ugly way from http://www.djangosnippets.org/snippets/600/ 我没有找到一个好的方法,所以我从http://www.djangosnippets.org/snippets/600/

try:
    import socket
    hostname = socket.gethostname().replace('.','_')
    exec "from host_settings.%s import *" % hostname
except ImportError, e:
    raise e

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM