如何从 Python 中的文件夹外部访问模块?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24868733/
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
How to access a module from outside your file folder in Python?
提问by Sean Francis N. Ballais
How can I access modules from another folder?
如何从另一个文件夹访问模块?
Here's the file structure:
这是文件结构:
/<appname>
/config
__init__.py
config.py
/test
test.py # I'm here
I wanted to access the functions from config.py from test.py . How would I do this?
Here is my import:
我想从 test.py 访问 config.py 中的功能。我该怎么做?
这是我的导入:
import config.config
When I run the test.py
script, it will always say:
当我运行test.py
脚本时,它总是会说:
ImportError: No module named config.config
Did I do something wrong?
我做错什么了吗?
采纳答案by aruisdante
The simplest way is to modify the sys.path
variable (it defines the import search path):
最简单的方法是修改sys.path
变量(它定义了导入搜索路径):
# Bring your packages onto the path
import sys, os
sys.path.append(os.path.abspath(os.path.join('..', 'config')))
# Now do your import
from config.config import *
回答by falsetru
Add the app directory to the module search path.
将 app 目录添加到模块搜索路径。
For example:
例如:
PYTHONPATH=/path/to/appname python test.py
回答by Hristo Ivanov
Yo can only import modules that are visible by your environment. You can check the environment using this.
您只能导入您的环境可见的模块。您可以使用它检查环境。
import sys
print sys.path
As you will see sys.path is a list so you can append elements to it:
正如您将看到的 sys.path 是一个列表,因此您可以向其附加元素:
sys.path.append('/path_to_app/config')
And you should be able to import your module.
你应该能够导入你的模块。
BTW: There is plenty of questions about this.
BTW:关于这个有很多问题。