对python比较熟悉和专业的过来看一下,from __future__ import absolute_import 的问题?
Python 3.3.2+ (default, Feb 28 2014, 00:52:16)
[GCC 4.8.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
===============================================
是这样:最近学习flask 和 celery, 引入celery的时候,遇到
SystemError: Parent module '' not loaded, cannot perform relative import
所以,找了一些资料看一下,有这些
https://docs.python.org/2/whatsnew/2.5.html#pep-328-absolute-and-relative-imports
http://blog.tankywoo.com/python/2013/10/07/python-relative-and-absolute-import.html
Once absolute imports are the default, import string will always find the standard library’s version. It’s suggested that users should begin using absolute imports as much as possible, so it’s preferable to begin writing from pkg import string in your code.
from
future
import absolute_import
#import string # This is error because `import string` will use the standard string module
from pkg import string
string.say_hello()
Relative imports are still possible by adding a leading period to the module name when using the from ... import form:
from
future
import absolute_import
from . import string # This is the same as `from pkg import string`
string.say_hello()
为什么按照帖子里面执行却报错?
(f3):~/g/f3/cc/pkg$ python main.py
Traceback (most recent call last):
File "main.py", line 7, in <module>
from . import string
SystemError: Parent module '' not loaded, cannot perform relative import
发现celery里面有这一句:
from __future__ import absolute_import
python3.3.2有没有必要使用absolute_import?。。。 【个人使用的环境是】
Python 3.3.2+ (default, Feb 28 2014, 00:52:16)
[GCC 4.8.1] on linux
补充:
有执行了一遍,贴出来
(f3):~/g/f3/cc/pkg$ python main.py
Traceback (most recent call last):
File "main.py", line 7, in <module>
from pkg import string
ImportError: No module named 'pkg'
(f3):~/g/f3/cc/pkg$ vim main.py
(f3):~/g/f3/cc/pkg$ python main.py
Traceback (most recent call last):
File "main.py", line 7, in <module>
from . import string
SystemError: Parent module '' not loaded, cannot perform relative import
Answers
搞清楚 Python 是怎么找包和模块的 !
python
(f3):~/g/f3/cc/pkg$ python main.py Traceback (most recent call last): File "main.py", line 7, in <module> from pkg import string ImportError: No module named 'pkg'
你的当前目前下没有名为
pkg
的模块,你需要到上一级目录,因为 Python 3 运行时只添加脚本所在目录到
sys.path
。
python
(f3):~/g/f3/cc/pkg$ python main.py Traceback (most recent call last): File "main.py", line 7, in <module> from . import string SystemError: Parent module '' not loaded, cannot perform relative import
相对导入只能在包(package)中执行,而你这样运行的话
main.py
不是包(只是个模块)。
你应该到上一级目录里运行
python -m pkg.main
。在上一级目录里才有
pkg
这个包,其下有个
main
模块,还有个
string
模块。