[英]ImportError: No module named <module name> for local module imports in Python
I am very new to Python and I have the following structure for a project:我是 Python 的新手,我的项目结构如下:
server/
├── config/
│ ├── __init__.py
│ ├── application.py
│ ├── dev.py
│ └── qa.py
├── lib/
│ ├── __init__.py
│ ├── redisdb.py
│ ├── logger.py
│ └── geo.py
└── scripts/
├── __init__.py
├── my_first_script.py
└── my_second_script.py
and in my_first_script.py
file, I have the following code:在
my_first_script.py
文件中,我有以下代码:
import pickle
from lib.redisdb import r
import re
import config.application as appconf
print( appconf.DOCUMENT_ENDPOINT )
partnerData = pickle.loads(r.get("partner_date_all"))
print( len(partnerData) )
When I run this code in the terminal using the command当我使用命令在终端中运行此代码时
python server/scripts/my_first_script.py
I am getting the following error:我收到以下错误:
Traceback (most recent call last):
File "my_first_script.py", line 3, in <module>
from lib.redisdb import r
ImportError: No module named lib.redisdb
I am using Python 2.7
version here.我这里使用的是
Python 2.7
版本。 When I checked with Python 3 also, I have the same error.当我也检查 Python 3 时,我有同样的错误。 Now how can I execute this file?
现在我该如何执行这个文件? If my code doesn't have imports from the other local modules, everything works just fine.
如果我的代码没有从其他本地模块导入,则一切正常。
Your modules are all siblings and you didn't not declare a parent package.你的模块都是兄弟姐妹,你没有声明父 package。
You could modify your structure this way so your modules can know each other.您可以通过这种方式修改您的结构,以便您的模块可以相互了解。
server/ (assuming this is your project root)
server/ (assuming you want to call your package "server")
├── __init__.py
├── server.py (your package entry point)
├── config/
│ ├── __init__.py
│ ├── application.py
│ ├── dev.py
│ └── qa.py
├── lib/
│ ├── __init__.py
│ ├── redisdb.py
│ ├── logger.py
│ └── geo.py
└── scripts/
├── __init__.py
├── my_first_script.py
└── my_second_script.py
And now your imports can refer to the parent package:现在您的导入可以参考父 package:
for example:例如:
# my_first_script.py
from server.config import application
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.