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

假设您的两个目录都是真正的Python包(其中包含__init__.py文件),这里是一个安全的解决方案,可以将模块相对于脚本的位置包含在内.

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

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 the 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、付费专栏及课程。

余额充值