【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: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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值