Python 从同一文件夹中的文件导入函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43865291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
import function from a file in the same folder
提问by Zemian
I'm building a Flask app with Python 3.5 following a tutorial, based on different import rules. By looking for similar questions, I managed to solve an ImportError based on importing from a nested folder by adding the folder to the path, but I keep failing at importing a function from a script in the same folder (already in the path). The folder structure is this:
我正在按照教程根据不同的导入规则使用 Python 3.5 构建 Flask 应用程序。通过寻找类似的问题,我设法通过将文件夹添加到路径来解决基于从嵌套文件夹导入的 ImportError,但是我一直无法从同一文件夹中的脚本(已在路径中)导入函数。文件夹结构是这样的:
DoubleDibz
├── app
│ ├── __init__.py
│ ├── api
│ │ ├── __init__.py
│ │ └── helloworld.py
│ ├── app.py
│ ├── common
│ │ ├── __init__.py
│ │ └── constants.py
│ ├── config.py
│ ├── extensions.py
│ ├── static
│ └── templates
└── run.py
In app.py I import a function from config.py by using this code:
在 app.py 中,我使用以下代码从 config.py 导入一个函数:
import config as Config
but I get this error:
但我收到此错误:
ImportError: No module named 'config'
I don't understand what's the problem, being the two files in the same folder. Thanks in advance
我不明白有什么问题,两个文件在同一个文件夹中。提前致谢
回答by macdrai
Have you tried
你有没有尝试过
import app.config as Config
It did the trick for me.
它对我有用。
回答by Juju
To import from the same folder you can do:
要从同一文件夹导入,您可以执行以下操作:
from .config import function_or_class_in_config_file
or to import the full config with the alias as you asked:
或者按照您的要求使用别名导入完整配置:
from ..app import config as Config
回答by stefan.stt
# imports all functions
import config
# you invoke it this way
config.my_function()
or
或者
# import specific function
from config import my_function
# you invoke it this way
my_function()
If the app.py is invoked not from the same folder you can do this:
如果 app.py 不是从同一个文件夹中调用的,您可以执行以下操作:
# csfp - current_script_folder_path
csfp = os.path.abspath(os.path.dirname(__file__))
if csfp not in sys.path:
sys.path.insert(0, csfp)
# import it and invoke it by one of the ways described above
回答by TimLanger
Another, shorter way would be:
另一种更短的方法是:
import .config as Config