[英]Import classes from another package Python
My source code directory (named my_dir
) is organized as follow: 我的源代码目录(名为my_dir
)组织如下:
my_dir
|
|-- pkg_1
| |
| |-- module_1.py
| |-- module_2.py
|
|-- src.py
In module_1.py
, I import module_2.py
by 在module_1.py
,我通过以下方式导入module_2.py
import module_2
But when I import module_1
in src.py
by 但是当我通过src.py
导入module_1
时
import module_1
An error is raised as the statement import module_2
in module_1.py
acts as if my working directory is pkg_1
instead of my_dir
. 引发错误的语句import module_2
在module_1.py
好像我的工作目录行为pkg_1
代替my_dir
。
How can it fix this ? 如何解决呢?
in module_1.py
import it as from . import module_2
在module_1.py
中module_1.py
导入from . import module_2
from . import module_2
and in src.py
import module_1 as from pkg_1 import module_1
from . import module_2
和src.py
进口module_1作为from pkg_1 import module_1
This is the cause of the misunderstanding: 这是造成误解的原因:
An error is raised as the statement
import module_2
inmodule_1.py
acts as if my working directory ispkg_1
instead ofmy_dir
. 引发错误的语句import module_2
在module_1.py
好像我的工作目录行为pkg_1
代替my_dir
。
First of all, when you import a package, the code in that package does not execute in a different working directory. 首先,在导入软件包时,该软件包中的代码不会在其他工作目录中执行。
The second mistake is that the working directory is not relevant at all, even if it did change. 第二个错误是,即使更改了工作目录,它也根本不相关。
Python code is organised into packages and modules. Python代码被组织为包和模块。 The interpreter searches for packages and modules within the python path. 解释器在python路径中搜索包和模块。
In the structure shown, my_dir
will be in python path if you run python src.py
. 在所示的结构中,如果您运行python src.py
, my_dir
将位于python路径中。 Then pkg_1
is a package whereas module_1
and module_2
are modules. 那么pkg_1
是一个程序包,而module_1
和module_2
是模块。 The easiest way to import module_2
is to use an absolute import: 导入module_2
的最简单方法是使用绝对导入:
import pkg_1.module_2
Alternatively, from within another module in pkg_1
you can use a relative import : 或者,可以从pkg_1
中的另一个模块中使用相对导入 :
from . import module_2
Try this: 尝试这个:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys;
# get path to this file.
path_this_file = os.path.dirname(os.path.abspath(__file__));
# add path to import files.
sys.path.insert(0, path_this_file + "/pkg_1");
import module_1, module_2;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.