简体   繁体   English

从另一个包Python导入类

[英]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_2module_1.py好像我的工作目录行为pkg_1代替my_dir

How can it fix this ? 如何解决呢?

in module_1.py import it as from . import module_2 module_1.pymodule_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_2src.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 in module_1.py acts as if my working directory is pkg_1 instead of my_dir . 引发错误的语句import module_2module_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.pymy_dir将位于python路径中。 Then pkg_1 is a package whereas module_1 and module_2 are modules. 那么pkg_1是一个程序包,而module_1module_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM