python 相对路径导入模块报错_python – 从相对路径导入模块

这篇博客介绍了如何在Python中安全地处理相对路径导入模块的问题,特别是当涉及到脚本位置、子目录以及不同执行环境时。通过修改sys.path,确保脚本能够找到并导入所需的模块,同时避免系统模块的冲突。文章还提到了__file__变量在某些情况下的不稳定性,并提供了替代解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

假设你的两个目录都是真正的python包(里面有__init__.py文件),这里是一个安全的解决方案,包括相对于脚本位置的模块。

我假设你想这样做,因为你需要包括一组模块与你的脚本。我在几个产品的生产中使用它,并且在许多特殊情况下工作,如:从另一个目录调用或使用python execute执行的脚本,而不是打开一个新的解释器。

import os, sys, inspect

# realpath() will make your script run, even if you symlink it :)

cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))

if cmd_folder not in sys.path:

sys.path.insert(0, cmd_folder)

# use this if you want to include modules from a subfolder

cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"subfolder")))

if cmd_subfolder not in sys.path:

sys.path.insert(0, cmd_subfolder)

# Info:

# cmd_folder = os.path.dirname(os.path.abspath(__file__)) # DO NOT USE __file__ !!!

# __file__ fails if script is called in different ways on Windows

# __file__ fails if someone does os.chdir() before

# sys.argv[0] also fails because it doesn't not always contains the path

作为奖励,这种方法确实让你强制Python使用你的模块,而不是系统上安装的模块。

警告!我真的不知道当前模块是在egg文件内发生了什么。也许它失败了。添加评论,如果你真的需要一个更好的解决方案,我可以投资更多的小时改善它。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值