Python多模块引用由此引发的相对路径混乱问题

作者:Likianta?Me 时间:2021-07-11 03:57:10 

多模块引用由此引发的相对路径混乱

当不同层级的 Python 模块相互调用时,我们会发现原本在一个模块中写死的相对路径会导致找不到文件的报错。

这种问题该怎么解决呢?

先说结论

复制下面的代码, 放到你的模块内 (或者保存为一个 .py 文件), 调用 relpath 函数即可.

def relpath(file):
   """ Always locate to the correct relative path. """
   from sys import _getframe
   from pathlib import Path
   frame = _getframe(1)
   curr_file = Path(frame.f_code.co_filename)
   return str(curr_file.parent.joinpath(file).resolve())

运行效果

Python多模块引用由此引发的相对路径混乱问题

特点

  • 不到 10 行代码

  • 无第三方库依赖

  • 使用简单, 只需把原先写死的相对路径, 替换为 relpath({之前写的路径}) 即可

  • 此外, Pycharm 还能够识别到文件参数, 在你键入时自动给出路径提示

Python多模块引用由此引发的相对路径混乱问题

更复杂的情况演示

someprj
|- relpath.py
|- A
   |- a.py
   |- AA
       |- aa.py
       |- AAA
           |- aaa.py
|- B
   |- b.txt
# A/a.py
def show_path():
   from relpath import relpath
   print(relpath('../B/b.txt'))

if __name__ == '__main__':
   from A.AA import aa
   from A.AA.AAA import aaa
   show_path()  # -> '/someprj/B/b.txt'
   aa.show_path()  # -> '/someprj/B/b.txt'
   aaa.show_path()  # -> '/someprj/B/b.txt'

# A/AA/aa.py
def show_path():
   from relpath import relpath
   print(relpath('../../B/b.txt'))

if __name__ == '__main__':
   from A import a
   from A.AA.AAA import aaa
   show_path()  # -> '/someprj/B/b.txt'
   a.show_path()  # -> '/someprj/B/b.txt'
   aaa.show_path()  # -> '/someprj/B/b.txt'

# A/AA/AAA/aaa.py
def show_path():
   from relpath import relpath
   print(relpath('../../../B/b.txt'))

if __name__ == '__main__':
   from A import a
   from A.AA import aa
   show_path()  # -> '/someprj/B/b.txt'
   a.show_path()  # -> '/someprj/B/b.txt'
   aa.show_path()  # -> '/someprj/B/b.txt'

来源:https://blog.csdn.net/Likianta/article/details/89299937

标签:Python,多模块,相对路径,混乱
0
投稿

猜你喜欢

  • Python标准异常和异常处理详解

    2021-02-23 05:10:36
  • python Django连接MySQL数据库做增删改查

    2023-11-14 10:44:35
  • PyTorch的SoftMax交叉熵损失和梯度用法

    2023-06-17 12:46:49
  • python中matplotlib的颜色及线条控制的示例

    2023-11-04 08:11:50
  • ASP.NET Core优雅的在开发环境保存机密(User Secrets)

    2023-07-15 20:25:37
  • 快速升级MySQL系统表

    2009-01-23 12:35:00
  • 一次性压缩Sqlserver2005中所有库日志的存储过程

    2012-01-29 17:58:28
  • python集合删除多种方法详解

    2021-12-06 07:59:51
  • scrapy-redis分布式爬虫的搭建过程(理论篇)

    2022-04-25 20:49:25
  • Python telnet登陆功能实现代码

    2022-08-13 01:52:56
  • python实现多层感知器

    2022-07-04 14:37:10
  • 如何使用Python程序完成描述性统计分析需求

    2021-01-11 22:11:20
  • python实现的web监控系统

    2022-01-28 20:31:57
  • 详解前端自动化工具gulp自动添加版本号

    2023-08-09 14:48:41
  • asp脚本延时 自定义的delay函数

    2008-04-07 12:59:00
  • String.indexOf 方法介绍

    2013-06-01 20:22:27
  • 在python中利用dict转json按输入顺序输出内容方式

    2021-10-26 15:17:23
  • Python中字典的基础介绍及常用操作总结

    2022-11-30 14:33:40
  • Python全栈之学习HTML

    2023-12-05 14:56:55
  • ASP强制刷新和判断文件地址是否存在

    2007-09-16 17:11:00
  • asp之家 网络编程 m.aspxhome.com