如何将函数或 class 从一个文件夹导入到另一个文件夹
How can i import function or class from one folder to another folder
我正在使用 python 3.6。我有以下文件夹结构:
main_directory
-- sub_directory_one
-- config.py
-- sub_directory_two
-- test.py
我想将函数或 class 从 config.py 导入到 test.py 。
我试过了
from sub_directory_one.config import class_name
from main_directory.sub_directory_one.config import class_name
但没有任何效果。
很少有人建议将项目添加到系统 path.But 我目前正在研究 mac 如果将其部署到 ubuntu 服务器会发生什么。
谢谢
如果您的子目录是(应该是)Python packages,请在这些目录中添加一个空的 __init__.py
文件。如果您然后从主目录 运行 您的主应用程序,您应该能够使用:
from sub_directory_one.config import class_name
或者,如果 config.py
和 test.py
是 Python 模块 ,无论出于何种实际原因,它们只是分开在不同的目录中,您应该将子目录添加到 Python 搜索路径。这可以通过在启动主应用程序之前设置环境变量 PYTHONPATH 或在导入这些模块之前在主脚本中扩展 Python 变量 sys.path
来完成。在这种情况下,您应该使用:
from config import class_name
有关 Python 模块和包的详细信息,请参阅 official documentation。
我正在使用 python 3.6。我有以下文件夹结构:
main_directory
-- sub_directory_one
-- config.py
-- sub_directory_two
-- test.py
我想将函数或 class 从 config.py 导入到 test.py 。 我试过了
from sub_directory_one.config import class_name
from main_directory.sub_directory_one.config import class_name
但没有任何效果。 很少有人建议将项目添加到系统 path.But 我目前正在研究 mac 如果将其部署到 ubuntu 服务器会发生什么。
谢谢
如果您的子目录是(应该是)Python packages,请在这些目录中添加一个空的 __init__.py
文件。如果您然后从主目录 运行 您的主应用程序,您应该能够使用:
from sub_directory_one.config import class_name
或者,如果 config.py
和 test.py
是 Python 模块 ,无论出于何种实际原因,它们只是分开在不同的目录中,您应该将子目录添加到 Python 搜索路径。这可以通过在启动主应用程序之前设置环境变量 PYTHONPATH 或在导入这些模块之前在主脚本中扩展 Python 变量 sys.path
来完成。在这种情况下,您应该使用:
from config import class_name
有关 Python 模块和包的详细信息,请参阅 official documentation。