zoukankan      html  css  js  c++  java
  • Python:Relative import 相对路径 ValueError: Attempted relative import in non-package

    使用相对的的 import 方式,只能在包里面;这样 “.” 就会按照name 找路径;

    如果主main运行的话__name__ = "__main__" 就找不到路径了。

    包含相对路径import 的python脚本不能直接运行,只能作为module被引用。原因正如手册中描述的,所谓相对路径其实就是相对于当前module的路径,但如果直接执行脚本,这个module的name就是“main”, 而不是module原来的name, 这样相对路径也就不是原来的相对路径了,导入就会失败,出现错误“ValueError: Attempted relative import in non-package”

    Note that both explicit and implicit relative imports are based on the name of the current module. Since the name of the main module is always"__main__", modules intended for use as the main module of a Python application should always use absolute imports.

    只能 从包外面 触发里面的相对路径调用;

    eg:执行外面的 z.py 触发里面 top/sub1/m1.py 使用相对路径

    GitHub 示例文件下载 rar_down

    #
    elative_import\topsub1m1.py
    print 'i am m1 
    from . import m2 
    ...from ..sub2 import sub2_sub'
    from . import m2  
    from ..sub2 import sub2_sub
    

    from . import m2 #同级目录

    from ..sub2 import sub2_sub # 上级目录

    #
    elative_importz.py  
    from top.sub1 import m1
    
  • 相关阅读:
    VS2013中设置大小写的快捷键
    cocos3.2版本中的一些新特性
    cocos2dx中的设计分辨率与屏幕适配策略
    cocos3.2中如何创建一个场景
    C++中的虚函数(类的向上转换,和向下转换)
    C++中的冒泡排序,选择排序,插入排序
    C++中的快速排序(使用vector和数组的不同)
    2440addr.h
    2440slib.h
    mmu.h
  • 原文地址:https://www.cnblogs.com/willowj/p/8082964.html
Copyright © 2011-2022 走看看