zoukankan      html  css  js  c++  java
  • 【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)
    
  • 相关阅读:
    基础网络技术--学习网络的的道路漫长啊
    华为nova8se和vivoS7e的区别哪个好
    Java.awt实现一个简单的围棋
    HashMap put原理详解(基于jdk1.8)
    Paper Pal:一个中英文论文及其代码大数据搜索平台
    【u116】最短路计数
    【u108】取数游戏
    【u106】3D模型
    【topcoder SRM 652 DIV2 250】ValueOfString
    【u103】绘制二叉树
  • 原文地址:https://www.cnblogs.com/dplearning/p/8659137.html
Copyright © 2011-2022 走看看