Python Import Error: I am getting error when importing function from package. Import error on test.py when performing mymath.multiply()
Python Import Error: I am getting error when importing function from package. Import error on test.py when performing mymath.multiply()
这是我的目录结构:
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'
当您 运行 python myscript.py
时,当前工作目录目录被添加到您的模块搜索路径中,因此该目录中的任何模块都是可导入的。
但是,当 mymath/__init__.py
尝试执行 from mymath import multiply
时,它找不到 mymath.py
,因为 mymath/
不在您的模块搜索路径中。
最佳解决方案是更改 mymath/__init__.py
以使用不同的导入语句:
from .mymath import multiply
这意味着"import multiply
from a module named mymath
in the same directory as this module."
这是我的目录结构:
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'
当您 运行 python myscript.py
时,当前工作目录目录被添加到您的模块搜索路径中,因此该目录中的任何模块都是可导入的。
但是,当 mymath/__init__.py
尝试执行 from mymath import multiply
时,它找不到 mymath.py
,因为 mymath/
不在您的模块搜索路径中。
最佳解决方案是更改 mymath/__init__.py
以使用不同的导入语句:
from .mymath import multiply
这意味着"import multiply
from a module named mymath
in the same directory as this module."