函数定义

__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:123456@127.0.0.1/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__的更多相关文章

  1. 【Python②】python之首秀

       第一个python程序 再次说明:后面所有代码均为Python 3.3.2版本(运行环境:Windows7)编写. 安装配置好python后,我们先来写第一个python程序.打开IDLE (P ...

  2. 【python】多进程锁multiprocess.Lock

    [python]多进程锁multiprocess.Lock 2013-09-13 13:48 11613人阅读 评论(2) 收藏 举报  分类: Python(38)  同步的方法基本与多线程相同. ...

  3. 【python】SQLAlchemy

    来源:廖雪峰 对比:[python]在python中调用mysql 注意连接数据库方式和数据操作方式! 今天发现了个处理数据库的好东西:SQLAlchemy 一般python处理mysql之类的数据库 ...

  4. 【python】getopt使用

    来源:http://blog.chinaunix.net/uid-21566578-id-438233.html 注意对比:[python]argparse模块 作者:limodou版权所有limod ...

  5. 【Python】如何安装easy_install?

    [Python]如何安装easy_install? http://jingyan.baidu.com/article/b907e627e78fe146e7891c25.html easy_instal ...

  6. 【Python】 零碎知识积累 II

    [Python] 零碎知识积累 II ■ 函数的参数默认值在函数定义时确定并保存在内存中,调用函数时不会在内存中新开辟一块空间然后用参数默认值重新赋值,而是单纯地引用这个参数原来的地址.这就带来了一个 ...

  7. 【Python】-NO.97.Note.2.Python -【Python 基本数据类型】

    1.0.0 Summary Tittle:[Python]-NO.97.Note.2.Python -[Python 基本数据类型] Style:Python Series:Python Since: ...

  8. 【Python】-NO.99.Note.4.Python -【Python3 条件语句 循环语句】

    1.0.0 Summary Tittle:[Python]-NO.99.Note.4.Python -[Python3 条件语句 循环语句] Style:Python Series:Python Si ...

  9. 【Python】-NO.98.Note.3.Python -【Python3 解释器、运算符】

    1.0.0 Summary Tittle:[Python]-NO.98.Note.3.Python -[Python3 解释器] Style:Python Series:Python Since:20 ...

随机推荐

  1. JavaScript实用的工具/类库

    Moment.js//JavaScript日期处理类库. Lodash.js//非常实用的工具库. MD5//加密. Numeral.js//格式化和数字四则运算. Pure.css//CSS模块.

  2. ThreadGroup解读

    我们的项目用到了ThreadGroup 把thread放到了threadGroup中,名称统一起来了: , , 5L, TimeUnit.MINUTES, ), new ThreadFactory() ...

  3. Fixing “Did you mean to run dotnet SDK commands?” error when running dotnet –version

    I recently installed the dotnet 1.11.0 Windows Server Hosting package which apparently installs the ...

  4. Go语言嵌入类型

    一.什么是嵌入类型 先看如下代码: type user struct { name string email string } type admin struct { user // Embedded ...

  5. Dijkstra算法——计算一个点到其他所有点的最短路径的算法

    迪杰斯特拉算法百度百科定义:传送门 gh大佬博客:传送门 迪杰斯特拉算法用来计算一个点到其他所有点的最短路径,是一种时间复杂度相对比较优秀的算法 O(n2)(相对于Floyd算法来说) 是一种单源最短 ...

  6. opencv 增强现实(二):特征点匹配

    import cv2 as cv import numpy as np # def draw_keypoints(img, keypoints): # for kp in keypoints: # x ...

  7. Linux内核参数

    vm.overcommit_memory 0 - 表示内核将检查是否有足够的可用内存供应用进程使用:如果有足够的可用内存,内存申请允许:否则,内存申请失败,并把错误返回给应用进程. 1 - 表示内核允 ...

  8. Codeforces 1077F1 Pictures with Kittens (easy version)(DP)

    题目链接:Pictures with Kittens (easy version) 题意:给定n长度的数字序列ai,求从中选出x个满足任意k长度区间都至少有一个被选到的最大和. 题解:$dp[i][j ...

  9. Dynamic Rankings ZOJ - 2112(主席树+树状数组)

    The Company Dynamic Rankings has developed a new kind of computer that is no longer satisfied with t ...

  10. 第三十七节、人脸检测MTCNN和人脸识别Facenet(附源码)

    在说到人脸检测我们首先会想到利用Harr特征提取和Adaboost分类器进行人脸检测(有兴趣的可以去一看这篇博客第九节.人脸检测之Haar分类器),其检测效果也是不错的,但是目前人脸检测的应用场景逐渐 ...