zoukankan      html  css  js  c++  java
  • [笔记]Python中模块互相调用的例子

    python中模块互相调用容易出错,经常是在本地路径下工作正常,切换到其他路径来调用,就各种模块找不到了。
    解决方法是通过__file__定位当前文件的真实路径,再通过sys.path.append()来获取相对路径更新$PATH即可。

    假设代码结构如下:

    - mod_a
        __init__.py     # 模块文件夹内必须有此文件
        aaa.py
    - mod_b
        __init__.py     # 模块文件夹内必须有此文件
        bbb.py
    - ccc.py
    
    • 调用同级模块

    如果aaa.py要调用bbb.py的内容,可以在aaa.py中如下写:

    import sys
    sys.path.append(osp.join(osp.dirname(__file__), '..'))  # 扫除路径迷思的关键!
    from mod_b.bbb import *
    
    • 调用下级模块

    如果ccc.py要调用bbb.py的内容,可以在ccc.py中如下写:

    from mod_b.bbb import *
    
    • 调用上级模块

    如果aaa.py要调用ccc.py的内容,可以在aaa.py中如下写:

    import sys
    sys.path.append(osp.join(osp.dirname(__file__), '..'))
    from ccc import *
    

    代码示例:

    aaa.py如下:

    # -*- coding: utf-8 -*-
    
    from __future__ import print_function
    import os.path as osp
    import sys
    sys.path.append(osp.join(osp.dirname(__file__), '..'))
    from mod_b.bbb import *
    from ccc import *
    
    def print_a():
      print('this is a')
      
    def _call_mod_b():
      print_a()
      print_b()
      
    def _call_mod_c():
      print_c()
    
    
    if __name__=='__main__':
      _call_mod_b()
      _call_mod_c()
    

    bbb.py如下:

    # -*- coding: utf-8 -*-
    
    from __future__ import print_function
    
    def print_b():
      print('this is b')
    
    
    if __name__=='__main__':
      pass
    

    ccc.py如下:

    # -*- coding: utf-8 -*-
    
    from __future__ import print_function
    from mod_b.bbb import *
    
    def print_c():
      print('this is c')
      
    def _call_mod_b():
      print_c()
      print_b()
      
    
    if __name__=='__main__':
      _call_mod_b()
    

    如此,当不管在何处调用aaa.py时,结果都一样,如下:

    this is a
    this is b
    this is c
    

    如果调用ccc.py,结果如下:

    this is c
    this is b
    
  • 相关阅读:
    【12】python模块:itsdangerous(生成临时身份令牌)
    python作业/练习/实战:下载QQ群所有人的头像
    【4】Python操作redis
    【7】Python网络请求:requests模块
    【6】Python网络请求:urllib模块
    python学习笔记:目录结构
    【9】Python接口开发:flask Demo实例
    【8】Python接口开发:PythonWEB框架之Flask
    前端学习笔记——引入css文件、样式优先级
    Yii2模型介绍
  • 原文地址:https://www.cnblogs.com/journeyonmyway/p/9492544.html
Copyright © 2011-2022 走看看