[英]Python3 error “ImportError: No module named” have __init__.py
I created a simple flask application and my directory structure looks like this: 我创建了一个简单的烧瓶应用程序,我的目录结构如下所示:
myproject
- src
-- models
--- __init__.py
-- views
--- errors.py
--- default.py
-- application.py
-- config.py
-- __init__.py
- test
-- test_myproject.py
Readme.md
setup.py
..
The application.py from the src look like this: 来自src的application.py看起来像这样:
from src.models import db
from src.views.errors import error_pages
from src.views.scoreboard import scoreboard
from src.config import config
The test_myproject looks like this: test_myproject看起来像这样:
from src.models import db, Result
from src.application import create_app
I use Pycharm to develop this and when I click run it works but when I try to run it via the command line python application.py
I get the following error: 我使用Pycharm来开发它,当我点击运行它工作,但当我尝试通过命令行
python application.py
运行它时,我收到以下错误:
Traceback (most recent call last):
File "src/application.py", line 18, in <module>
from src.models import db
ImportError: No module named 'src'
Runnint the unittests with python -m unittest
works. 使用
python -m unittest
工作运行单元测试。
If I change the imports from application.py to: 如果我将application.py中的导入更改为:
from models import db
from views.errors import error_pages
from views.scoreboard import scoreboard
from config import config
It will work when I run it via the command line, however the tests won't work anymore. 当我通过命令行运行它时它会工作,但是测试将不再起作用。
File ".../src/application.py", line 18, in <module>
from models import db
ImportError: No module named 'models'
What am I doing wrong? 我究竟做错了什么?
You said that you're running python application.py
, which suggests that your working directory is src
. 你说你正在运行
python application.py
,这表明你的工作目录是src
。 To be able to import modules under src.*
(without playing with PYTHONPATH) you should run Python from the myproject
directory instead. 为了能够在
src.*
下导入模块(不使用PYTHONPATH),你应该从myproject
目录运行Python。
Consider either moving application.py
to myproject
or running it with python src/application.py
. 考虑将
application.py
移动到myproject
或使用python src/application.py
运行它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.