django - ImportError using python if __name__ == "__main__"
问题描述
I currently inherited a codebase that looks something like this.
project
manage.py
|_ config
|_ settings
|_ wsgi.py
|_ project
|_ app1
|_ app2
|.... <-- many more Django apps
|_ a_new_app
|_ __init__.py
|_ run.py
|_ foo.py
|_ bar.py
I added a new app with some .py
files which imports from other apps too in the same package and other app packages too in the project. All is well till I tried to run
python project/a_new_app/run.py
Then I started getting import error here is how my run.py
looks.
# run.py
from project.a_new_app.foo import Foo
class App():
def method(self, key):
data = {"some-key": Foo}
return data.get(key)
.... more methods here
if __name__ == "__main__":
app = App()
app.loop_forever()
I got this error
File "project/a_new_app/run.py", line 7, in <module>
from project.a_new_app.foo import Foo
ImportError: No module named project.a_new_app.foo
My working directory is /user/me/PycharmProjects/project
, Thanks.
解决方案
from project.a_new_app.foo import Foo
For this import to work, you need the outer project
directory (the one containing manage.py
and the inner project
directory) to be on the Python path.
However, run.py
is two directories deeper than that, in project/a_new_app
. Therefore you need to add ../..
to the python path at the top of the module.
import sys
sys.path.append('../..')
from project.a_new_app.foo import Foo
...
推荐阅读
- c - 返回多个值的输入数组函数
- git - 从运行 git 1.7.1 的 RHEL 6.8 获取 401 Unauthorized cloning TFS 2017 git repo over https
- javafx - 如何使用 JFoenix 显示对话框 - JAVAFX
- javascript - 动态充气的herf点击后不会下载文件
- git - 用 git 创建一个开发分支
- javascript - 如何使用 jQuery 获取表单输入数据?
- html - 如何防止容器中的内容与背景图像中的文本重叠?
- linux - 根据大小和出现将文件拆分为多个文件
- postgresql - 部署使用 PostgreSQL 数据库的应用程序
- ruby - Ruby:File.open 以变量作为文件名的奇怪行为