Home  >  Q&A  >  body text

module - python模块from import语句相对导入,加不加点号有什么区别?

python版本为2.7

目录结构

$ ls -R
.:
t.py  util/

./util:
__init__.py  __init__.pyc  db.py  db.pyc

内容

util/db.py

# coding=utf-8          
                        
var=100                 
def show():             
    print var           

t.py

# coding=utf-8         
                    
from .util.db import var # util包前面加点
                        
print var               
if __name__=='__main__':
    print var           

运行报错

$ python t.py
Traceback (most recent call last):
  File "t.py", line 3, in <module>
    from .util.db import var
ValueError: Attempted relative import in non-package

提示不能在non-package下导入。

在当前目录下新建__init__.py后依然是相同错误。

但是将util前面的点号去掉之后可以正常输出,为什么呢?

谢谢

巴扎黑巴扎黑2741 days ago1062

reply all(2)I'll reply

  • 高洛峰

    高洛峰2017-04-18 10:36:44

    Relative import can only be used in the same package, and files in the package cannot be run independently

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-18 10:36:44

    t.py is executed as the main script. If there is a from. method in it, an error will be reported (only modules in the package use this method)
    Even if _init_ is added, you still execute it directly, and the method has not changed. You should change to python -m xxx.t

    reply
    0
  • Cancelreply