python__import__

Posted 匡子语

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python__import__相关的知识,希望对你有一定的参考价值。

函数定义

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

Import a module. Because this function is meant for use by the Python
interpreter and not for general use it is better to use
importlib.import_module() to programmatically import a module.

The globals argument is only used to determine the context;
they are not modified.  The locals argument is unused.  The fromlist
should be a list of names to emulate ``from name import ...‘‘, or an
empty list to emulate ``import name‘‘.
When importing a module from a package, note that __import__(‘A.B‘, ...)
returns package A when fromlist is empty, but its submodule B when
fromlist is not empty.  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.    

name:引用模块名称,如‘sys’, ‘libs/module.a‘
fromlist:子模块列表,如果name是a.b的格式,则必须把b加入fromlist中

用途

  • 动态导入模块

例子

import os

def test():
    datetime = __import__(‘datetime‘)
    print datetime.datetime.now()
    a = __import__("module.module_a", globals={}, locals={}, fromlist=["module_a"], level=-1)
    print a.sub(x, y)


test()

调用不同目录的模块

  • 应该先sys.path.append(模块所在路径),然后再用相对路径引用

例:
在下面这个例子中,由于celery调用,运行路径跟当前路径不同,直接引用module.module_a会报错:无法找到该模块,同时如果__import__的第一个参数用绝对路径,会报错:不可使用文件名引用
正确方法就是先在系统路径中加入当前路径,然后用相对路径引用

from celery import Celery
import os
import sys

current_path = os.path.dirname(os.path.realpath(__file__))
sys.path.append(current_path)

app = Celery(‘tasks‘, backend=‘amqp‘, broker=‘amqp://test:[email protected]/testhost‘)

@app.task
def add(x, y):
    a = __import__("module.module_a", globals={}, locals={}, fromlist=["module_a"], level=-1)
    print a.add(x, y)



以上是关于python__import__的主要内容,如果未能解决你的问题,请参考以下文章

python 反射(__import__getattr)

Python学习from __future__ import print_function用法

Python 同级目录import报错

Python:import 与__import__()

Python函数 __import__()

from __future__ import print_function的作用