Python 3.6 中的相对导入
Relative import in Python 3.6
我想在 Python 3.
中使用相对导入
我的项目:
main_folder
- __init__.py
- run.py
- tools.py
我想在 run.py(MyClass
在 __init__.py 中声明):
from . import MyClass
在run.py中:
from .tools import my_func
一个ImportError
被加注。
或者,使用绝对导入,在 PyCharm 中调试不起作用,库从安装的包中获取,而不是我的目录。
我知道一种方法,但很糟糕:
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
如何在我的项目中使用这个导入?
当你使用PyCharm时,它会自动使当前模块成为主模块,所以像from . import <module>
这样的相关语句将不起作用。 read more here.
要解决您的问题,请将 __init__.py
和 tools.py
文件放入 sub-directory
main_directory/
run.py
sub_directory/
__init__.py
tools.py
在您的 run.py
文件中,将以下内容写入您的导入语句
from sub_directory import tools
from sub_directory.__init__ import MyClass
编辑: 如@9000 所述,您可以编写 from sub_directory import MyClass
并实现相同的目的。
我想在 Python 3.
中使用相对导入我的项目:
main_folder
- __init__.py
- run.py
- tools.py
我想在 run.py(MyClass
在 __init__.py 中声明):
from . import MyClass
在run.py中:
from .tools import my_func
一个ImportError
被加注。
或者,使用绝对导入,在 PyCharm 中调试不起作用,库从安装的包中获取,而不是我的目录。
我知道一种方法,但很糟糕:
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
如何在我的项目中使用这个导入?
当你使用PyCharm时,它会自动使当前模块成为主模块,所以像from . import <module>
这样的相关语句将不起作用。 read more here.
要解决您的问题,请将 __init__.py
和 tools.py
文件放入 sub-directory
main_directory/
run.py
sub_directory/
__init__.py
tools.py
在您的 run.py
文件中,将以下内容写入您的导入语句
from sub_directory import tools
from sub_directory.__init__ import MyClass
编辑: 如@9000 所述,您可以编写 from sub_directory import MyClass
并实现相同的目的。