简体   繁体   English

Python无法导入包

[英]Python can't import package

I have a package structure like: 我有一个像这样的包结构:

thePackage/
    __init__.py
    moduleA.py
    moduleB.py
    moduleC.py

The __init__.py file contains __init__.py文件包含

from . import moduleA

For simplicity I cd into the directory containing the foler thePackage . 为了简单起见,我cd到含有foler目录thePackage

When I try to import thePackage I get the error: 当我尝试import thePackage ,出现错误:

Traceback (most recent call last):

  File "<ipython-input-10-5fe9a18b3124>", line 1, in <module>
import thePackage

  File "C:\thePackage\__init__.py", line 2, in <module>
from . import moduleA

ImportError: cannot import name 'moduleA'

I've read a few posts like Importing packages in Python , but still can't figure out my problem. 我读过一些文章,例如《 用Python导入软件包》 ,但仍然无法弄清我的问题。 The accepted answer in that post suggests I should be able to import the submodule moduleA by import thePackage.moduleA , but when I try this I get the exact same error. 那篇文章中接受的答案建议我应该能够通过import thePackage.moduleA导入子模块import thePackage.moduleA ,但是当我尝试这样做时,我会得到完全相同的错误。

How can I important the package thePackage? 我如何重要包装thePackage?

Also, how can I just import moduleA? 另外,如何导入模块A?

from thePackage import moduleA

I encountered the issue while using Spyder and Python3.4 . 我在使用SpyderPython3.4时遇到了问题。

When I closed and restarted Spyder , I was able to import the package using import thePackage , and I was able to import moduleA using import thePackage.moduleA . 关闭并重新启动Spyder ,我可以使用import thePackage ,也可以使用import thePackage.moduleA

Also, originally when I first tried to import the module using import thePackage , it failed. 同样,最初当我第一次尝试使用import thePackage导入模块时,它失败了。 At this point I might have modified and saved the __init__.py . 此时,我可能已经修改并保存了__init__.py Then I probably tried to import the module again using import thePackage , but maybe this doesn't always try to import the newly saved versions of thePackage . 然后我可能尝试使用import thePackage再次import thePackage ,但是也许这并不总是尝试导入新保存的thePackage版本。 Thus, I recommend trying 因此,我建议尝试

import importlib
importlib.reload(thePackage)

to force the import of the newly saved version of thePackage . 强制导入新保存的thePackage版本。

you could try 你可以尝试

    sudo apt-get install python-setuptools

found it at https://bitbucket.org/pypa/setuptools/issues/368/module-object-has-no-attribute-packaging , and it helped me when I was having challenges installing pyttsx, https://bitbucket.org/pypa/setuptools/issues/368/module-object-has-no-attribute-packaging上找到它,当我在安装pyttsx遇到困难时,它对我有帮助,

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

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