问题:Python错误“ ImportError:未命名模块”

Python安装在本地目录中。

我的目录树如下所示:

(local directory)/site-packages/toolkit/interface.py

我的代码在这里:

(local directory)/site-packages/toolkit/examples/mountain.py

要运行该示例,我编写python mountain.py,并且在代码中有:

from toolkit.interface import interface

我得到错误:

Traceback (most recent call last):
  File "mountain.py", line 28, in ?
    from toolkit.interface import interface
ImportError: No module named toolkit.interface

我已经检查过了sys.path,这里有目录/site-packages。另外,我__init__.py.bin在toolkit文件夹中有该文件,以向Python指示这是一个软件包。我__init__.py.bin在示例目录中也有一个。

我不知道为什么Python在时找不到文件sys.path。有任何想法吗?可以是权限问题吗?我需要执行许可吗?

Python is installed in a local directory.

My directory tree looks like this:

(local directory)/site-packages/toolkit/interface.py

My code is in here:

(local directory)/site-packages/toolkit/examples/mountain.py

To run the example, I write python mountain.py, and in the code I have:

from toolkit.interface import interface

And I get the error:

Traceback (most recent call last):
  File "mountain.py", line 28, in ?
    from toolkit.interface import interface
ImportError: No module named toolkit.interface

I have already checked sys.path and there I have the directory /site-packages. Also, I have the file __init__.py.bin in the toolkit folder to indicate to Python that this is a package. I also have a __init__.py.bin in the examples directory.

I do not know why Python cannot find the file when it is in sys.path. Any ideas? Can it be a permissions problem? Do I need some execution permission?


回答 0

根据您对orip帖子的评论,我想这是发生了什么:

  1. __init__.py在Windows上进行了编辑。
  2. Windows编辑器添加了一些不可打印的内容,也许是回车符(Windows中的行尾是CR / LF;在Unix中是LF),或者是CTRL-Z(Windows文件末尾)。
  3. 您使用WinSCP将文件复制到Unix框中。
  4. WinSCP认为:“这不是基本文字;我将添加.bin扩展名以指示二进制数据。”
  5. 缺少__init__.py(现在称为__init__.py.bin)意味着python无法将工具包理解为一个包。
  6. __init__.py在适当的目录中创建,一切正常…?

Based on your comments to orip’s post, I guess this is what happened:

  1. You edited __init__.py on windows.
  2. The windows editor added something non-printing, perhaps a carriage-return (end-of-line in Windows is CR/LF; in unix it is LF only), or perhaps a CTRL-Z (windows end-of-file).
  3. You used WinSCP to copy the file to your unix box.
  4. WinSCP thought: “This has something that’s not basic text; I’ll put a .bin extension to indicate binary data.”
  5. The missing __init__.py (now called __init__.py.bin) means python doesn’t understand toolkit as a package.
  6. You create __init__.py in the appropriate directory and everything works… ?

回答 1

是否

(local directory)/site-packages/toolkit

有一个__init__.py

为了使进口步行通过你的目录中的每个目录必须有一个__init__.py文件。

Does

(local directory)/site-packages/toolkit

have a __init__.py?

To make import walk through your directories every directory must have a __init__.py file.


回答 2

我在LPTHW中进行此练习时遇到了非常相似的事情。我永远无法让Python识别出我正在从其调用的目录中有文件。但是我最终能够使它工作。我所做的以及我的建议是尝试以下操作:

(注意:从您的第一篇文章中,我假设您使用的是基于* NIX的计算机,并且正在通过命令行运行,因此此建议是针对性的。自从我运行Ubuntu以来,我就是这样做的。)

1)将目录(cd)更改为文件所在目录上方的目录。在这种情况下,您将尝试运行mountain.py文件,并尝试调用toolkit.interface.py位于单独目录中的模块。在这种情况下,您将转到包含两个文件路径的目录(或换句话说,这两个文件的路径共享的最近目录)。在这种情况下是toolkit目录。

2)在tookit目录中时,在命令行上输入以下代码行:

export PYTHONPATH=.

这会将您的PYTHONPATH设置为“。”,这基本上意味着您的PYTHONPATH现在将在您当前所在目录(甚至更重要的是,您所在目录的子目录分支)中查找所有被调用的文件。因此,它不只是看在你的当前目录,但在所有可在目录中的当前目录)。

3)在上述步骤中设置完PYTHONPATH之后,请从当前目录(该toolkit目录)运行模块。Python现在应该找到并加载您指定的模块。

希望这可以帮助。我自己对此感到非常沮丧。

I ran into something very similar when I did this exercise in LPTHW; I could never get Python to recognise that I had files in the directory I was calling from. But I was able to get it to work in the end. What I did, and what I recommend, is to try this:

(NOTE: From your initial post, I am assuming you are using an *NIX-based machine and are running things from the command line, so this advice is tailored to that. Since I run Ubuntu, this is what I did)

1) Change directory (cd) to the directory above the directory where your files are. In this case, you’re trying to run the mountain.py file, and trying to call the toolkit.interface.py module, which are in separate directories. In this case, you would go to the directory that contains paths to both those files (or in other words, the closest directory that the paths of both those files share). Which in this case is the toolkit directory.

2) When you are in the tookit directory, enter this line of code on your command line:

export PYTHONPATH=.

This sets your PYTHONPATH to “.”, which basically means that your PYTHONPATH will now look for any called files within the directory you are currently in, (and more to the point, in the sub-directory branches of the directory you are in. So it doesn’t just look in your current directory, but in all the directories that are in your current directory).

3) After you’ve set your PYTHONPATH in the step above, run your module from your current directory (the toolkit directory). Python should now find and load the modules you specified.

Hope this helps. I was quite frustrated with this myself.


回答 3

在* nix上,还要确保正确配置了PYTHONPATH,尤其是它具有以下格式:

 .:/usr/local/lib/python

(请注意.:开头,以便它也可以在当前目录中搜索。)

它也可能在其他位置,具体取决于版本:

 .:/usr/lib/python
 .:/usr/lib/python2.6
 .:/usr/lib/python2.7 and etc.

On *nix, also make sure that PYTHONPATH is configured correctly, especially that it has this format:

 .:/usr/local/lib/python

(Mind the .: at the beginning, so that it can search on the current directory, too.)

It may also be in other locations, depending on the version:

 .:/usr/lib/python
 .:/usr/lib/python2.6
 .:/usr/lib/python2.7 and etc.

回答 4

我解决了自己的问题,并将总结出错误的地方和解决方案:

该文件需要完全调用__init__.py。如果扩展名不同(例如在我的情况下),.py.bin则Python无法在目录中移动,因此找不到模块。要编辑文件,您需要使用Linux编辑器,例如vinano。如果您使用Windows编辑器,则会写一些隐藏的字符。

影响它的另一个问题是,我的根目录安装了另一个Python版本,因此,如果有人正在使用python的本地安装,请确保运行程序的Python安装是本地Python。要检查这一点,只需执行which python,然后查看可执行文件是否在您的本地目录中。如果不是,请更改路径,但请确保本地Python目录位于另一个Python目录之前。

I solved my own problem, and I will write a summary of the things that were wrong and the solution:

The file needs to be called exactly __init__.py. If the extension is different such as in my case .py.bin then Python cannot move through the directories and then it cannot find the modules. To edit the files you need to use a Linux editor, such as vi or nano. If you use a Windows editor this will write some hidden characters.

Another problem that was affecting it was that I had another Python version installed by the root, so if someone is working with a local installation of python, be sure that the Python installation that is running the programs is the local Python. To check this, just do which python, and see if the executable is the one that is in your local directory. If not, change the path, but be sure that the local Python directory is before than the other Python.


回答 5

一个简单的解决方案是使用来安装模块,python -m pip install <library-name>而不是pip install <library-name> 在管理员限制的情况下使用sudo

an easy solution is to install the module using python -m pip install <library-name> instead of pip install <library-name> you may use sudo in case of admin restrictions


回答 6

要将目录标记为包,您需要一个名为的文件__init__.py,这有帮助吗?

To mark a directory as a package you need a file named __init__.py, does this help?


回答 7

使用PyCharm(属于JetBrains套件的一部分),您需要将脚本目录定义为Source:
Right Click > Mark Directory as > Sources Root

Using PyCharm (part of the JetBrains suite) you need to define your script directory as Source:
Right Click > Mark Directory as > Sources Root


回答 8

您正在阅读此答案,表明您__init__.py来对地方了,已经安装了所有依赖项,并且仍在获取ImportError

我遇到了类似的问题,除了我的程序在使用PyCharm运行时可以正常运行,但是当我从终端运行时出现上述错误。进一步挖掘之后,我发现PYTHONPATH该项目目录中没有该条目。因此,我将PYTHONPATH每个Import语句设置为在PyCharm上有效,但不能在terminal上使用

export PYTHONPATH=$PYTHONPATH:`pwd`  (OR your project root directory)

使用sys.pathas 的另一种方法是:

import sys
sys.path.insert(0,'<project directory>') OR
sys.path.append('<project directory>')

您可以根据要搜索项目的顺序使用插入/追加。

You are reading this answer says that your __init__.py is in the right place, you have installed all the dependencies and you are still getting the ImportError.

I was facing a similar issue except that my program would run fine when ran using PyCharm but the above error when I would run it from the terminal. After digging further, I found out that PYTHONPATH didn’t have the entry for the project directory. So, I set PYTHONPATH per Import statement works on PyCharm but not from terminal:

export PYTHONPATH=$PYTHONPATH:`pwd`  (OR your project root directory)

There’s another way to do this using sys.path as:

import sys
sys.path.insert(0,'<project directory>') OR
sys.path.append('<project directory>')

You can use insert/append based on the order in which you want your project to be searched.


回答 9

对我来说,那真是愚蠢。我使用来安装该库,pip3 install但正在运行程序python program.py而不是python3 program.py

For me, it was something really stupid. I installed the library using pip3 install but was running my program as python program.py as opposed to python3 program.py.


回答 10

对。您需要包含该__init__.py文件的目录,该文件是用于初始化程序包的文件。在这里,看看这个

__init__.py文件是使Python将目录视为包含包所必需的;这样做是为了防止具有通用名称的目录(例如字符串)无意间隐藏了稍后在模块搜索路径中出现的有效模块。在最简单的情况下,__init__.py可以只是一个空文件,但它也可以为该程序包执行初始化代码或设置__all__变量,如后所述。

Yup. You need the directory to contain the __init__.py file, which is the file that initializes the package. Here, have a look at this.

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.


回答 11

  1. 您必须在与要导入文件相同的目录中拥有文件__ init__.py。
  2. 您不能尝试从PYTHONPATH上配置的2个文件夹中导入具有相同名称的文件。

例如:/ etc / environment

PYTHONPATH = $ PYTHONPATH:/ opt /文件夹1:/ opt /文件夹2

/ opt / folder1 / foo

/ opt / folder2 / foo

并且,如果您尝试导入foo文件,python将不知道您要哪个。

从foo import … >>> importerror:没有名为foo的模块

  1. You must have the file __ init__.py in the same directory where it’s the file that you are importing.
  2. You can not try to import a file that has the same name and be a file from 2 folders configured on the PYTHONPATH.

eg: /etc/environment

PYTHONPATH=$PYTHONPATH:/opt/folder1:/opt/folder2

/opt/folder1/foo

/opt/folder2/foo

And, if you are trying to import foo file, python will not know which one you want.

from foo import … >>> importerror: no module named foo


回答 12

我的两分钱:

在此处输入图片说明

吐:

Traceback (most recent call last):
      File "bash\bash.py", line 454, in main
        import bosh
      File "Wrye Bash Launcher.pyw", line 63, in load_module
        mod = imp.load_source(fullname,filename+ext,fp)
      File "bash\bosh.py", line 69, in <module>
        from game.oblivion.RecordGroups import MobWorlds, MobDials, MobICells, \
    ImportError: No module named RecordGroups

这让我很困惑-遍历各种帖子,暗示了丑陋的syspath hacks(如您所见,我__init__.py在那里)。好吧,事实证明game / oblivion.py和game / oblivion混淆了python,并吐出了相当无用的“没有名为RecordGroups的模块”。我对解决此问题和/或记录此(相同名称)行为的链接感兴趣->编辑(2017.01.24)-看看如果我具有相同名称的模块和软件包怎么办?有趣的是,通常程序包具有优先权,但显然我们的启动程序违反了此规则。

编辑(2015.01.17):我没有提到我们使用此处剖析的自定义启动器

My two cents:

enter image description here

Spit:

Traceback (most recent call last):
      File "bash\bash.py", line 454, in main
        import bosh
      File "Wrye Bash Launcher.pyw", line 63, in load_module
        mod = imp.load_source(fullname,filename+ext,fp)
      File "bash\bosh.py", line 69, in <module>
        from game.oblivion.RecordGroups import MobWorlds, MobDials, MobICells, \
    ImportError: No module named RecordGroups

This confused the hell out of me – went through posts and posts suggesting ugly syspath hacks (as you see my __init__.py were all there). Well turns out that game/oblivion.py and game/oblivion was confusing python which spit out the rather unhelpful “No module named RecordGroups”. I’d be interested in a workaround and/or links documenting this (same name) behavior -> EDIT (2017.01.24) – have a look at What If I Have a Module and a Package With The Same Name? Interestingly normally packages take precedence but apparently our launcher violates this.

EDIT (2015.01.17): I did not mention we use a custom launcher dissected here.


回答 13

Linux:导入的模块位于/usr/local/lib/python2.7/dist-packages中

如果您使用的是用C语言编译的模块,请不要忘了在之后对.so文件进行chmod修改sudo setup.py install

sudo chmod 755 /usr/local/lib/python2.7/dist-packages/*.so

Linux: Imported modules are located in /usr/local/lib/python2.7/dist-packages

If you’re using a module compiled in C, don’t forget to chmod the .so file after sudo setup.py install.

sudo chmod 755 /usr/local/lib/python2.7/dist-packages/*.so

回答 14

就我而言,问题是我链接到debug pythonboost::Python,它要求扩展名是FooLib_d.pyd,而不仅仅是FooLib.pyd; 重命名文件或更新CMakeLists.txt属性可修复该错误。

In my case, the problem was I was linking to debug python & boost::Python, which requires that the extension be FooLib_d.pyd, not just FooLib.pyd; renaming the file or updating CMakeLists.txt properties fixed the error.


回答 15

如果您尝试了上面提供的所有方法但都失败了,则也许您的模块内置模块具有相同的名称。或者,文件夹中存在的同名sys.path模块比模块具有更高的优先级。

要调试,请说出您的from foo.bar import baz抱怨ImportError: No module named bar。更改为import foo; print foo,将显示的路径foo。是您所期望的吗?

如果不是,请重命名foo或使用绝对导入

If you have tried all methods provided above but failed, maybe your module has the same name as a built-in module. Or, a module with the same name existing in a folder that has a high priority in sys.path than your module’s.

To debug, say your from foo.bar import baz complaints ImportError: No module named bar. Changing to import foo; print foo, which will show the path of foo. Is it what you expect?

If not, Either rename foo or use absolute imports.


回答 16

我的问题是,__init__.py实际上需要添加其父目录时,我将带有文件的目录添加到了PYTHONPATH中。

My problem was that I added the directory with the __init__.py file to PYTHONPATH, when actually I needed to add its parent directory.


回答 17

对于所有仍然有此问题的人。我相信Pycharm与进口商品混淆了。对我来说,当我写“从命名空间导入某物”时,前一行用红色下划线标出,表示有错误,但可以。但是,“从.namespace导入某些内容”不会带有下划线,但也无法正常工作。

尝试

try:
    from namespace import something 
except NameError:
    from .namespace import something

To all those who still have this issue. I believe Pycharm gets confused with imports. For me, when i write ‘from namespace import something’, the previous line gets underlined in red, signaling that there is an error, but works. However ”from .namespace import something’ doesn’t get underlined, but also doesn’t work.

Try

try:
    from namespace import something 
except NameError:
    from .namespace import something

回答 18

通过编写修复了我的问题print (sys.path),发现尽管进行了全新安装,python仍在使用过期的软件包。删除这些使python自动使用正确的软件包。

Fixed my issue by writing print (sys.path) and found out that python was using out of date packages despite a clean install. Deleting these made python automatically use the correct packages.


回答 19

就我而言,因为我正在使用PyCharm和PyCharm在项目文件夹中为每个项目创建一个“ venv”,但这只是python的一个迷你环境。尽管您已经在Python中安装了所需的库,但是在您的自定义项目“ venv”中,该库不可用。这是PyCharm中发生“导入错误:没有名为xxxxxx的模块”的真正原因。要解决此问题,必须通过以下步骤将库添加到项目自定义环境中:

  • 在PyCharm中,从菜单“文件”->“设置”
  • 在设置对话框中,项目:XXXProject->项目解释器
  • 点击“添加”按钮,它将显示“可用包”对话框
  • 搜索您的库,单击“安装软件包”
  • 然后,所有需要的软件包将安装在项目自定义“ venv”文件夹中。

设置对话框

请享用。

In my case, because I’m using PyCharm and PyCharm create a ‘venv’ for every project in project folder, but it is only a mini env of python. Although you have installed the libraries you need in Python, but in your custom project ‘venv’, it is not available. This is the real reason of ‘ImportError: No module named xxxxxx’ occurred in PyCharm. To resolve this issue, you must add libraries to your project custom env by these steps:

  • In PyCharm, from menu ‘File’->Settings
  • In Settings dialog, Project: XXXProject->Project Interpreter
  • Click “Add” button, it will show you ‘Available Packages’ dialog
  • Search your library, click ‘Install Package’
  • Then, all you needed package will be installed in you project custom ‘venv’ folder.

Settings dialog

Enjoy.


回答 20

在经历了同样的问题后,我发现我的解决方案是pyc从项目中删除所有文件,似乎这些缓存的文件以某种方式导致了此错误。

我发现最简单的方法是在Windows资源管理器中导航到我的项目文件夹并搜索*.pyc,然后选择所有(Ctrl+ A)并删除它们(Ctrl+ X)。

可能我可以通过删除特定pyc文件来解决问题,但我从未尝试过

After just suffering the same issue I found my resolution was to delete all pyc files from my project, it seems like these cached files were somehow causing this error.

Easiest way I found to do this was to navigate to my project folder in Windows explorer and searching for *.pyc, then selecting all (Ctrl+A) and deleting them (Ctrl+X).

Its possible I could have resolved my issues by just deleting the specific pyc file but I never tried this


回答 21

我遇到了同样的问题:Import error。此外,该库已正确安装了100%。问题的根源是在我的PC 3版本上安装了python(anaconda数据包)。这就是为什么没有将库安装到正确的位置的原因。之后,我只是在我的IDE PyCharm中更改为python的正确版本。

I faced the same problem: Import error. In addition the library’ve been installed 100% correctly. The source of the problem was that on my PC 3 version of python (anaconda packet) have been installed). This is why the library was installed no to the right place. After that I just changed to the proper version of python in the my IDE PyCharm.


回答 22

我有同样的错误。这是因为有人在与脚本相同的文件夹中创建了一个文件夹,该文件夹的名称与我从其他位置导入的模块冲突。它没有导入外部模块,而是查看了该文件夹内部,该文件夹显然不包含预期的模块。

I had the same error. It was caused by somebody creating a folder in the same folder as my script, the name of which conflicted with a module I was importing from elsewhere. Instead of importing the external module, it looked inside this folder which obviously didn’t contain the expected modules.


回答 23

我遇到了同样的问题(Python 2.7 Linux),我找到了解决方案,我想分享一下。就我而言,我的结构如下:

Booklet
-> __init__.py
-> Booklet.py
-> Question.py
default
-> __init_.py
-> main.py

在“ main.py”中,我尝试了以下所有组合,但均未成功:

from Booklet import Question
from Question import Question
from Booklet.Question import Question
from Booklet.Question import *
import Booklet.Question
# and many othet various combinations ...

解决方案比我想象的要简单得多。我将文件夹“ Booklet”重命名为“ booklet”,仅此而已。现在,Python可以通过在“ main.py”中使用以下代码来正常导入Question类:

from booklet.Booklet import Booklet
from booklet.Question import Question
from booklet.Question import AnotherClass

由此我可以得出结论,像“小册子”之类的包名称(文件夹)必须以小写开头,否则Python会将其与类名和文件名混淆。

显然,这不是您的问题,但是John Fouhy的回答非常好,并且该线程具有几乎所有可能导致此问题的东西。因此,这是一回事,我希望这可以对其他人有所帮助。

I had the same problem (Python 2.7 Linux), I have found the solution and i would like to share it. In my case i had the structure below:

Booklet
-> __init__.py
-> Booklet.py
-> Question.py
default
-> __init_.py
-> main.py

In ‘main.py’ I had tried unsuccessfully all the combinations bellow:

from Booklet import Question
from Question import Question
from Booklet.Question import Question
from Booklet.Question import *
import Booklet.Question
# and many othet various combinations ...

The solution was much more simple than I thought. I renamed the folder “Booklet” into “booklet” and that’s it. Now Python can import the class Question normally by using in ‘main.py’ the code:

from booklet.Booklet import Booklet
from booklet.Question import Question
from booklet.Question import AnotherClass

From this I can conclude that Package-Names (folders) like ‘booklet’ must start from lower-case, else Python confuses it with Class names and Filenames.

Apparently, this was not your problem, but John Fouhy’s answer is very good and this thread has almost anything that can cause this issue. So, this is one more thing and I hope that maybe this could help others.


回答 24

就我而言,我要包含package.egg文件夹的路径,而不是其下面的实际软件包。我将软件包复制到顶层,并且可以正常工作。

In my case I was including the path to package.egg folder rather than the actual package underneath. I copied the package to top level and it worked.


回答 25

这对我有用:__init__.py在父文件夹中创建文件(在您的情况下,在site-packages文件夹中)。并像这样导入:

from site-packages.toolkit.interface import interface

希望它对您也有用!

This worked for me: Created __init__.py file inside parent folder (in your case, inside site-packages folder). And imported like this:

from site-packages.toolkit.interface import interface

Hope it will be useful for you as well !


回答 26

在linux服务器上尝试 dos2unix script_name

pyc使用命令删除所有(如果有的话)文件find . -name '*.pyc' -delete

如果您在Windows上处理脚本,请重新运行

In linux server try dos2unix script_name

(remove all (if there is any) pyc files with command find . -name '*.pyc' -delete)

and re run in the case if you worked on script on windows


回答 27

就我而言,我是sys.path.insert()用来导入本地模块的,并且是module not found从另一个库中获取的。我不得不把sys.path.insert()进口的商品放在下面module not found。我想最好的做法是放在sys.path.insert()进口的底部。

In my case, I was using sys.path.insert() to import a local module and was getting module not found from a different library. I had to put sys.path.insert() below the imports that reported module not found. I guess the best practice is to put sys.path.insert() at the bottom of your imports.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。