[英]Import of files in one folder from another folder
I know there are similar questions asked but what I found is not very clear to me in this simple setting.我知道有人问过类似的问题,但在这个简单的设置中,我发现的并不是很清楚。 Given this directory tree how can I import a function from
file1.py
into file2
(we call the interpreter from the file2.py
)?鉴于此目录树,我如何将 function 从
file1.py
导入到file2
(我们从file2.py
调用解释器)? I would like this setting to work independently on where main_folder
is, that is if I copy main_folder
to a different directory, the imports would still work well.我希望这个设置在
main_folder
所在的位置独立工作,也就是说,如果我将main_folder
复制到不同的目录,导入仍然可以正常工作。
main_folder
folder1
file1.py (with a function func())
folder2
file2.py
You can use SourceFileLoader
from importlib.machinery
to import from a path.您可以使用
importlib.machinery
中的SourceFileLoader
从路径导入。
So you can use:所以你可以使用:
# file2.py
from importlib.machinery import SourceFileLoader
PATH = "../folder1/file1.py"
file1 = SourceFileLoader("module.name", PATH).load_module()
Or if you would import
from a package then you can use:或者,如果您要从 package
import
,那么您可以使用:
# file2.py
from folder1.file1 import func
If you would like to use the package approach then you will need to run it from main_folder
.如果您想使用 package 方法,那么您需要从
main_folder
运行它。
Also you can add absolute path to sys.path
.您也可以将绝对路径添加到
sys.path
。
sys.path
A list of strings that specifies the search path for modules.
指定模块搜索路径的字符串列表。 Initialized from the environment variable
PYTHONPATH
, plus an installation-dependent default.从环境变量
PYTHONPATH
初始化,加上依赖于安装的默认值。As initialized upon program startup, the first item of this list,
path[0]
, is the directory containing the script that was used to invoke the Python interpreter.在程序启动时初始化时,此列表的第一项
path[0]
是包含用于调用 Python 解释器的脚本的目录。 If the script directory is not available (eg if the interpreter is invoked interactively or if the script is read from standard input),path[0]
is the empty string, which directs Python to search modules in the current directory first.如果脚本目录不可用(例如,如果交互调用解释器或从标准输入读取脚本),
path[0]
是空字符串,它指示 Python 首先搜索当前目录中的模块。 Notice that the script directory is inserted before the entries inserted as a result ofPYTHONPATH
.请注意,在
PYTHONPATH
插入的条目之前插入了脚本目录。A program is free to modify this list for its own purposes.
程序可以出于自己的目的自由修改此列表。 Only strings and bytes should be added to
sys.path
;只有字符串和字节应该添加到
sys.path
; all other data types are ignored during import.导入期间将忽略所有其他数据类型。
import sys
from pathlib import Path
sys.path.append(str(Path(sys.path[0]).resolve().parent / "folder1"))
import file1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.