简体   繁体   English

python无法导入模块

[英]python unable to import module

I have my program set up using packages as followed:我使用包设置了我的程序,如下所示:

-base
    -init.py
    -base_class.py
-test
    -init.py
    -test.py

When I do the import statement from base.base_class import BaseClass in the test.py I get this error when running it:当我在test.py from base.base_class import BaseClass执行 import 语句时from base.base_class import BaseClass我在运行它时收到此错误:

from base.base_class import BaseClass
ImportError: No module named base.base_class

How can I import this module?如何导入此模块?

at the top of test.py add在 test.py 的顶部添加

import sys
sys.path.append("..")

base is not a folder on the path...once you change this it should work base 不是路径上的文件夹......一旦你改变它它应该可以工作

or put test.py in the same folder as base.或将 test.py 放在与 base 相同的文件夹中。 or move base to somewhere that is on your path或将基地移动到您路径上的某个地方

你需要在你导入的每个文件夹中有一个__init__.py文件

您必须在 python 目录中创建一个名为“ __init__.py ”的文件,然后“Python”会将该目录理解为一个 Python 包。

there are 3 things you can do:你可以做三件事:

add an init.py file to each folder向每个文件夹添加一个init.py文件

add sys.path.append("Folder") to the topsys.path.append("Folder")添加到顶部

or use imp and do;或使用imp and do;

import imp
foo = imp.load_source('filename', 'File\Directory\filename.py')

then foo will be the name of the module for example foo.method()然后 foo 将是模块的名称,例如foo.method()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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