【python相对路径】为何使用了相对路径的文件只能作为模块或者库运行?

python绝对引用和相对引用
Python杂谈: init.py的作用

当python文件A中使用到相对路径导入B时,直接运行A文件会显示找不到B。但将A作为模块或者库的一部分,在其他文件中导入A,此时又能顺利找到B。具体可看以下内容:

1.文件结构

在这里插入图片描述

2.文件代码

2.1 package/file1.py

def file1_fun():
    pass

if __name__ == '__main__':
    print("this is file1")
   
2.2 package/file2.py
from . import file1

def file2_fun():
    pass

if __name__ == '__main__':
    print("this is file2")

2.3 file3.py
from package.file2 import file2_fun

if __name__ == "__main__":
    file2_fun()

3.问题阐述

查看代码我们可知,file2文件里通过相对路径法导入了file1文件,但是直接右键运行file2文件,会出现以下错误:无法找到file1文件

Traceback (most recent call last):
  File "/home/hovexb/CODE/import_test/package/file2.py", line 1, in <module>
    from . import file1
ImportError: cannot import name 'file1'

而将含相对路径的file2作为module,在file3中导入file2,则file3正常运行

4.原因分析

PEP 328可知:

Relative imports use a module’s name attribute to determine that module’s position in the package hierarchy. If the module’s name does not contain any package information (e.g. it is set to ‘main’) then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.

相对路径引用使用__name__这一属性指示模块在包里的位置信息,当直接运行file2.py时,__name__=__main__则认为该文件位于根模块,而不管该文件真正的位置。
但file2被用做模块在file3中导入时,file2中的__name__=package.file2,由此file2就能通过相对路径正确定位到file1文件。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值