请原谅我问的问题这么肤浅,但是我已经搜索了很多资料,花了2个小时依然找不到症结所在,所以只能提问了
环境windows10+python3.4.4
先把目录组织给出来
rootdir
libraries
__init__.py
classes.py
configs.py
functions.py
scripts
__init__.py
script_of_folder_process.py
__init__.py
上面有三个包,一个是rootdir,剩余两个scripts和libraries是rootdir的子包
现在我希望能够在script_of_folder_process.py引用libraries内的classes和configs模块,其中classes内有我自己写的一个Mysql类,import代码如下:
import os
import os.path
import time
from ..libraries.classes import Mysql
from ..libraries.configs import DIR_MYSQL_CFG, FOLDER_MATCH_LOG_DIR
很遗憾的是出现了如下错误:
Traceback (most recent call last):
File "E:\workspace\Auto_Project_Manage_System\scripts\script_of_folder_process.py", line 13, in <module>
from ..libraries.classes import Mysql
SystemError: Parent module '' not loaded, cannot perform relative import
因此我测试了一下,即使改变了import,也依然无法访问到这两个模块
import os
import os.path
import time
from ..libraries import classes
from ..libraries import configs
错误如下:
Traceback (most recent call last):
File "E:\workspace\Auto_Project_Manage_System\scripts\script_of_folder_process.py", line 13, in <module>
from ..libraries import classes
SystemError: Parent module '' not loaded, cannot perform relative import
但是我若是将script_of_folder_process.py改变位置,放在rootdir下,即:
rootdir
libraries
__init__.py
classes.py
configs.py
functions.py
scripts
__init__.py
__init__.py
script_of_folder_process.py
并改变import为这样:
import os
import os.path
import time
from libraries.classes import Mysql
from libraries.configs import DIR_MYSQL_CFG,FOLDER_MATCH_LOG_DIR
代码便能正常运行,请问我的问题到底出在哪里?怎样才能访问父目录下的另一个包的模块?
高洛峰2017-04-17 17:34:01
Reference: http://stackoverflow.com/questions/14132789/python-relative-imports-for-the-billionth-time#answer-14132912
So you can return to rootdir’s 上级目录
, 然后用-m
parameter execution and it’s done:
python -m rootdir.scripts.script_of_folder_process
高洛峰2017-04-17 17:34:01
There seems to be a discussion about this error in issue 18018. The solution is here, but I don’t know how to use it... If anyone knows, please let me know~