从相对路径导入模块 [英] Import a module from a relative path
问题描述
如何在给定相对路径的情况下导入 Python 模块?
How do I import a Python module given its relative path?
例如,如果dirFoo
包含Foo.py
和dirBar
,并且dirBar
包含Bar.py
,如何将 Bar.py
导入到 Foo.py
中?
For example, if dirFoo
contains Foo.py
and dirBar
, and dirBar
contains Bar.py
, how do I import Bar.py
into Foo.py
?
这是一个视觉表示:
dirFoo\
Foo.py
dirBar\
Bar.py
Foo
希望包含 Bar
,但重组文件夹层次结构不是一个选项.
Foo
wishes to include Bar
, but restructuring the folder hierarchy is not an option.
推荐答案
假设你的两个目录都是真正的 Python 包(里面有 __init__.py
文件),这里是一个安全的解决方案用于包含相对于脚本位置的模块.
Assuming that both your directories are real Python packages (do have the __init__.py
file inside them), here is a safe solution for inclusion of modules relatively to the location of the script.
我假设您想这样做,因为您需要在脚本中包含一组模块.我在几个产品的生产中使用它,并在许多特殊场景中工作,例如:从另一个目录调用的脚本或使用 python execute 执行的脚本,而不是打开一个新的解释器.
I assume that you want to do this, because you need to include a set of modules with your script. I use this in production in several products and works in many special scenarios like: scripts called from another directory or executed with python execute instead of opening a new interpreter.
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 使用您的模块,而不是系统上安装的模块.
As a bonus, this approach does let you force Python to use your module instead of the ones installed on the system.
警告!当当前模块位于 egg
文件中时,我真的不知道发生了什么.它也可能失败了.
Warning! I don't really know what is happening when current module is inside an egg
file. It probably fails too.
这篇关于从相对路径导入模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!