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前面的点号去掉之后可以正常输出,为什么呢?
谢谢
Relative import can only be used in the same package, and files in the package cannot be run independently
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