当包名称仅在运行时已知时,如何使用 __import__() 导入包?

发布于 2024-07-26 11:50:20 字数 393 浏览 7 评论 0 原文

我有一个消息文件夹(包),其中包含 __init__.py 文件和另一个模块 messages_en.py 。 在 __init__.py 中,如果我导入 messages_en 它可以工作,但是 __import__ 失败并显示“ImportError:没有名为 messages_en 的模块”

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

我曾经认为“导入” x' 只是 __import__('x') 的另一种表达方式

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')

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

享受孤独 2024-08-02 11:50:20

如果是路径问题,则应使用 level 参数(来自 文档):

__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.

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.
只为一人 2024-08-02 11:50:20

添加全局参数对我来说就足够了:

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

事实上,这里只需要 __name__

__import__('messages_en', globals={"__name__": __name__})

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__})
烟酉 2024-08-02 11:50:20

__import__ 是一个由 import 语句调用的内部函数。 在日常编码中,您不需要(或不想)

从 python 文档中调用 __import__

例如,语句 import spam 会生成类似于以下代码的字节码

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

:另一方面,语句 from spam.ham import Eggs, sausage as saus 会产生

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

更多信息:
http://docs.python.org/library/functions.html

__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

送舟行 2024-08-02 11:50:20

请务必将模块目录附加到您的 python 路径。

您的路径(Python 搜索模块和文件时所经过的目录列表)存储在 sys 模块的 path 属性中。 由于路径是一个列表,因此您可以使用追加方法将新目录添加到路径中。

例如,要将目录 /home/me/mypy 添加到路径中:

import sys
sys.path.append("/home/me/mypy") 

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") 
美人迟暮 2024-08-02 11:50:20

我知道这个问题是关于 __import__() 函数,但我认为如果您使用 Python 2.7 或更高版本,则 importlib 包最适合运行时包导入doc 中建议:

注意:以编程方式导入模块应使用 import_module() 而不是此函数。

可能的问题: 这是在 python 2.7 中引入的:

2.7 版本中的新增功能。

此模块是 Python 3.1 中功能更齐全的同名软件包中可用模块的一小部分,它提供了导入的完整实现。 此处提供的内容可帮助轻松从 2.7 过渡到 3.1。

在您的情况下,您可以使用:

import importlib

messages = importlib.import_module('messages_en')

另外,如果您想指定包名称,则 from messages import messages_en 可以写为:

importlib.import_module('.messages_en', 'messages ')

请注意 .messages_en 中的 . 用于相对路径解析,如 此处

... name 参数以绝对或相对方式指定要导入的模块(例如 pkg.mod 或 ..mod)。 如果以相对术语指定名称,则必须将 package 参数设置为包的名称,该包的名称将充当解析包名称的锚点(例如 import_module('..mod', 'pkg.subpkg')将导入 pkg.mod)。

I understand that this question is about the __import__() function but I think the importlib package is best suited for run-time package imports if you are using Python 2.7 or above as advised in the doc:

Note: Programmatic importing of modules should use import_module() instead of this function.

Possible Gotcha: This was introduced in python 2.7:

New in version 2.7.

This module is a minor subset of what is available in the more full-featured package of the same name from Python 3.1 that provides a complete implementation of import. What is here has been provided to help ease in transitioning from 2.7 to 3.1.

In your case, you may use:

import importlib

messages = importlib.import_module('messages_en')

Also, if you wanted to specify the package name, then from messages import messages_en may be written as:

importlib.import_module('.messages_en', 'messages')

Note the . in .messages_en used for relative path resolution as described here:

... The name argument specifies what module to import in absolute or relative terms (e.g. either pkg.mod or ..mod). If the name is specified in relative terms, then the package argument must be set to the name of the package which is to act as the anchor for resolving the package name (e.g. import_module('..mod', 'pkg.subpkg') will import pkg.mod).

伪装你 2024-08-02 11:50:20

你可以试试这个:

messages == __import__('Foo.messages_en', fromlist=['messages_en'])

You could try this:

messages == __import__('Foo.messages_en', fromlist=['messages_en'])
清风夜微凉 2024-08-02 11:50:20

您需要手动导入动态包路径的顶层包。

例如,在文件的开头我写:

import sites

然后在代码中这对我有用:

target = 'some.dynamic.path'
my_module = __import__ ('sites.%s.fabfile' % target, fromlist=["sites.%s" % target])

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])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文