Python导入错误:从包中导入函数时出现错误。执行mymath.multiply()时,在test.py上导入错误

时间:2019-09-27 14:53:08

标签: python python-import importerror

这是我的目录结构:

test.py
mymath/
    __init__.py
    mymath.py

test.py

import mymath
mymath.multiply()

__ init __。py

from mymath
import multiply

mymath.py

def multiply():

当我跑步时:

python3 test.py

我得到了错误:

Traceback (most recent call last):
  File "test.py", line 2, in <module>
    import mymath
  File "/home/kcb/python-scripts/mymath/__init__.py", line 1, in <module>
    from mymath import multiply
ImportError: cannot import name 'multiply'

1 个答案:

答案 0 :(得分:0)

运行python myscript.py时,会将当前工作目录目录添加到模块搜索路径,因此该目录中的所有模块都是可导入的。

但是,mymath/__init__.py尝试执行from mymath import multiply时,找不到mymath.py,因为mymath/不在模块搜索路径中。

最好的解决方案是将mymath/__init__.py更改为使用不同的import语句:

from .mymath import multiply

这意味着“从与此模块位于同一目录的名为multiply 的模块中导入mymath