我有这样的文件夹结构:
application
├── app
│ └── folder
│ └── file.py
└── app2
└── some_folder
└── some_file.py
如何从file.py或some_file.py中导入函数?我尝试了:
from application.app.folder.file import func_name
但它不起作用。
我有这样的文件夹结构:
application
├── app
│ └── folder
│ └── file.py
└── app2
└── some_folder
└── some_file.py
如何从file.py或some_file.py中导入函数?我尝试了:
from application.app.folder.file import func_name
但它不起作用。
当前回答
据我所知,直接在要导入的函数的文件夹中添加__init__.py文件即可完成此任务。
其他回答
我多次遇到同一个问题,所以我想分享我的解决方案。
Python版本:3.X
以下解决方案适用于在Python 3.X版本中开发应用程序的人,因为自2020年1月1日以来,Python 2不受支持。
项目结构
在python3中,由于隐式命名空间包,项目子目录中不需要__init__.py。请参见Python 3.3中的包是否不需要init.py+
Project
├── main.py
├── .gitignore
|
├── a
| └── file_a.py
|
└── b
└── file_b.py
问题陈述
在file_b.py中,我想在文件夹a下的file_a.py中导入一个类a。
解决
#1快速但肮脏的方式
不安装软件包,就像您当前正在开发一个新项目
使用try-catch检查是否存在错误。代码示例:
import sys
try:
# The insertion index should be 1 because index 0 is this file
sys.path.insert(1, '/absolute/path/to/folder/a') # the type of path is string
# because the system path already have the absolute path to folder a
# so it can recognize file_a.py while searching
from file_a import A
except (ModuleNotFoundError, ImportError) as e:
print("{} fileure".format(type(e)))
else:
print("Import succeeded")
#2安装软件包
安装应用程序后(在本文中,不包括安装教程)
你可以简单地
try:
from __future__ import absolute_import
# now it can reach class A of file_a.py in folder a
# by relative import
from ..a.file_a import A
except (ModuleNotFoundError, ImportError) as e:
print("{} fileure".format(type(e)))
else:
print("Import succeeded")
编码愉快!
您可以使用importlib导入模块,其中您希望使用如下字符串从文件夹中导入模块:
import importlib
scriptName = 'Snake'
script = importlib.import_module('Scripts\\.%s' % scriptName)
这个示例有一个main.py,它是上面的代码,然后是一个名为Scripts的文件夹,然后您可以通过更改scriptName变量从这个文件夹中调用所需的任何内容。然后可以使用脚本引用此模块。例如,如果我在Snake模块中有一个名为Hello()的函数,您可以通过这样做来运行该函数:
script.Hello()
我已经在Python 3.6中测试过了
我认为一种特别的方法是使用环境变量PYTHONPATH,如文档中所述:Python2,Python3
# Linux & OSX
export PYTHONPATH=$HOME/dirWithScripts/:$PYTHONPATH
# Windows
set PYTHONPATH=C:\path\to\dirWithScripts\;%PYTHONPATH%
当模块位于平行位置时,如问题所示:
application/app2/some_folder/some_file.py
application/app2/another_folder/another_file.py
这种速记使一个模块对另一个模块可见:
import sys
sys.path.append('../')
以防有人仍在寻找解决方案。这对我有用。
Python将包含您启动的脚本的文件夹添加到PYTHONPATH中,因此如果您运行
python application/app2/some_folder/some_file.py
只有文件夹application/app2/some_folder被添加到路径(而不是执行命令的基本目录)。相反,将文件作为模块运行,并在some_folder目录中添加__init__.py。
python -m application.app2.some_folder.some_file
这将把基本目录添加到python路径,然后可以通过非相对导入访问类。