How can I import a package using __import__() when

2019-01-22 20:27发布

I have a messages folder(package) with __init__.py file and another module messages_en.py inside it. In __init__.py if I import messages_en it works, but __import__ fails with "ImportError: No module named messages_en"

import messages_en # it works
messages = __import__('messages_en') # it doesn't ?

I used to think 'import x' is just another way of saying __import__('x')

6条回答
一夜七次
2楼-- · 2019-01-22 21:16

If it is a path problem, you should use the level argument (from docs):

__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module

Level is used to determine whether to perform
absolute or relative imports.  -1 is the original strategy of attempting
both absolute and relative imports, 0 is absolute, a positive number
is the number of parent directories to search relative to the current module.
查看更多
虎瘦雄心在
3楼-- · 2019-01-22 21:18

__import__ is an internal function called by import statement. In everyday coding you don't need (or want) to call __import__

from python documentation:

For example, the statement import spam results in bytecode resembling the following code:

spam = __import__('spam', globals(), locals(), [], -1)

On the other hand, the statement from spam.ham import eggs, sausage as saus results in

_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], -1)
eggs = _temp.eggs
saus = _temp.sausage

more info: http://docs.python.org/library/functions.html

查看更多
冷血范
4楼-- · 2019-01-22 21:19

Be sure to append the modules directory to your python path.

Your path (the list of directories Python goes through to search for modules and files) is stored in the path attribute of the sys module. Since the path is a list you can use the append method to add new directories to the path.

For instance, to add the directory /home/me/mypy to the path:

import sys
sys.path.append("/home/me/mypy") 
查看更多
再贱就再见
5楼-- · 2019-01-22 21:19

You need to manually import the top package of your dynamic package path.

For example in the beginning of the file i write:

import sites

then later in code this works for me:

target = 'some.dynamic.path'
my_module = __import__ ('sites.%s.fabfile' % target, fromlist=["sites.%s" % target])
查看更多
Luminary・发光体
6楼-- · 2019-01-22 21:23

Adding the globals argument is sufficient for me:

__import__('messages_en', globals=globals())

In fact, only __name__ is needed here:

__import__('messages_en', globals={"__name__": __name__})
查看更多
甜甜的少女心
7楼-- · 2019-01-22 21:26

You could try this:

messages == __import__('Foo.messages_en', fromlist=['messages_en'])
查看更多
登录 后发表回答