如何在 Django Settings.py 中导入另一个 Python 3 文件?
How to Import Another Python 3 File in Django Settings.py?
我正在使用 Python 3.
我在同一目录中有两个 Python 文件:first.py 和 second.py。
在first.py开头,我用:
from second import *
但是,它returns出现以下错误信息:
ModuleNotFoundError: No module named 'second'
我应该如何在 first.py 中导入它?
更新:为了阐明我的具体用例,我试图在 Django 中拆分我的 settings.py。我有一个 settings.py 主文件和另一个只包含机密信息的文件。我关注 this following documentation,它在 settings.py 中使用以下行:
from settings_local import *
请注意 settings_local.py 在同一目录中。但是,它 returns 出现以下错误消息:
ModuleNotFoundError: No module named 'settings_local'
我知道文档说 "Some of the examples listed below need to be modified for compatibility with Django 1.4 and later." 但我不知道如何在 Python 中使用它 3.
您可以通过这种方式将文件添加到 Python
import sys
sys.path.insert(0, '/path/to/application/app/folder')
import file
you can create __init__.py in current directory.
那么你可以使用:
from second import *
需要 init.py 文件才能使 Python 将目录视为包含包;这样做是为了防止具有通用名称(例如字符串)的目录无意中隐藏模块搜索路径中稍后出现的有效模块。在最简单的情况下,init.py 可以只是一个空文件,但它也可以执行包的初始化代码或设置 __all__variable,稍后描述。
您应该能够自动将文件所在的目录添加到 PATH
,然后导入另一个文件,使用此:
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
import second
我刚找到解决方案:
from .settings_local import *
而不是:
from settings_local import *
我在 this thread 中找到了解决方案。
您可以使用以下代码片段:
from .settings_local import *
这是相对导入。 More Info here and here
我正在使用 Python 3. 我在同一目录中有两个 Python 文件:first.py 和 second.py。 在first.py开头,我用:
from second import *
但是,它returns出现以下错误信息:
ModuleNotFoundError: No module named 'second'
我应该如何在 first.py 中导入它?
更新:为了阐明我的具体用例,我试图在 Django 中拆分我的 settings.py。我有一个 settings.py 主文件和另一个只包含机密信息的文件。我关注 this following documentation,它在 settings.py 中使用以下行:
from settings_local import *
请注意 settings_local.py 在同一目录中。但是,它 returns 出现以下错误消息:
ModuleNotFoundError: No module named 'settings_local'
我知道文档说 "Some of the examples listed below need to be modified for compatibility with Django 1.4 and later." 但我不知道如何在 Python 中使用它 3.
您可以通过这种方式将文件添加到 Python
import sys
sys.path.insert(0, '/path/to/application/app/folder')
import file
you can create __init__.py in current directory.
那么你可以使用:
from second import *
需要 init.py 文件才能使 Python 将目录视为包含包;这样做是为了防止具有通用名称(例如字符串)的目录无意中隐藏模块搜索路径中稍后出现的有效模块。在最简单的情况下,init.py 可以只是一个空文件,但它也可以执行包的初始化代码或设置 __all__variable,稍后描述。
您应该能够自动将文件所在的目录添加到 PATH
,然后导入另一个文件,使用此:
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
import second
我刚找到解决方案:
from .settings_local import *
而不是:
from settings_local import *
我在 this thread 中找到了解决方案。
您可以使用以下代码片段:
from .settings_local import *
这是相对导入。 More Info here and here