Python 3从子文件夹导入类问题 [英] Python 3 import class from subfolder problem

查看:352
本文介绍了Python 3从子文件夹导入类问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于子文件夹的导入类,我有一个奇怪的问题.

I have a strange problem regarding import classes from subfolders.

我正在使用Python 3.6,因此子文件夹中不需要__init__.py.

I'm using Python 3.6, therefore an __init__.py should be not required in the subfolders.

我具有以下文件结构:

root
├── script.py (main)
└── custom
    ├── class1.py
    └── class2.py


这是script.py:

from custom.class1 import Class1
from custom.class2 import Class2

if __name__ == '__main__':
    cl1 = Class1()
    cl2 = Class2()


这是class1.py:

class Class1():
    def __init__(self):
        print('Class1')

if __name__ == '__main__':
    cl1 = Class1()


这是class2.py,它也导入了class1:


This is class2.py, which imports also class1:

from class1 import Class1

class Class2():
    def __init__(self):
        cl1 = Class1()
        print('Class2')

if __name__ == '__main__':
    cl2 = Class2()


现在是问题所在:


And now the problem:

当我在custom子文件夹中运行python class1.py时,它没有错误.

It works without error, when i am running python class1.py in the custom subfolder.

当我在custom子文件夹中运行python class2.py时,它没有错误.

It works without error, when i am running python class2.py in the custom subfolder.

但是当我在root文件夹中运行python script.py时,出现以下错误:

But when i am running python script.py in the root folder, i get the following error:

Traceback (most recent call last):
  File .... in <module>
    from custom.class2 import Class2
  File .... line 1, in <module>
    from class1 import Class1
ModuleNotFoundError: No module named 'class1'

如何以某种方式解决该问题,以使custom子文件夹中的脚本可以单独运行,并且root文件夹中的脚本也可以工作?

How can this be fixed in a way, that the scripts in the custom subfolders can be run on its own and also the script in the root folder works?

推荐答案

问题是您正在script.py内部运行custom.class2,这意味着在运行custom.class2时,您仍位于root目录中

The problem is that you are running custom.class2 inside of script.py, which means while running custom.class2, you are still in the root directory.

要解决此问题,应将class2.py中的from class1 import Class1替换为from custom.class1 import Class1.

To fix this, you should replace from class1 import Class1 from class2.py with from custom.class1 import Class1.

如果您需要能够从任何工作目录中运行文件,则可以用以下内容替换其内容:

If you need to be able to run the file from any working directory, you may replace it's contents with this:

import os
import sys

path = os.path.abspath(os.path.dirname(__file__))
if not path in sys.path:
    sys.path.append(path)

from class1 import Class1

class Class2():
    def __init__(self):
        cl1 = Class1()
        print('Class2')

if __name__ == '__main__':
    cl2 = Class2()

代码将文件的路径添加到sys.path列表中,该列表包含可从中导入模块的不同路径.

The code adds the file's path in to the sys.path list, which holds different paths from which you can import modules.

这篇关于Python 3从子文件夹导入类问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆