尝试运行Python脚本时出现“ ImportError:未命名模块”

问题:尝试运行Python脚本时出现“ ImportError:未命名模块”

我正在尝试运行一个脚本,该脚本除其他外将启动python脚本。我收到一个ImportError:没有名为…的模块,但是,如果我启动ipython并通过解释器以相同的方式导入相同的模块,则该模块将被接受。

怎么回事,我该如何解决?我试图了解python如何使用PYTHONPATH,但是我感到非常困惑。任何帮助将不胜感激。

I’m trying to run a script that launches, amongst other things, a python script. I get a ImportError: No module named …, however, if I launch ipython and import the same module in the same way through the interpreter, the module is accepted.

What’s going on, and how can I fix it? I’ve tried to understand how python uses PYTHONPATH but I’m thoroughly confused. Any help would greatly appreciated.


回答 0

由于命令行IPython解释器使用当前路径的方式与单独进程(例如IPython笔记本,外部进程等)的方式不同,因此会出现此问题。IPython将寻找要导入的模块,这些模块不仅可以在sys.path中找到,而且可以在当前工作目录中找到。从命令行启动解释器时,您正在操作的当前目录与在ipython中启动的目录相同。如果运行

import os
os.getcwd() 

您会看到这是真的。

但是,假设您使用的是ipython笔记本,请运行,os.getcwd()而当前的工作目录是您告诉笔记本在ipython_notebook_config.py文件中操作笔记本的文件夹(通常使用该c.NotebookManager.notebook_dir设置)。

解决方案是为python解释器提供您的模块路径。最简单的解决方案是将该路径附加到sys.path列表中。在您的笔记本中,首先尝试:

import sys
sys.path.append('my/path/to/module/folder')

import module-of-interest

如果这不起作用,则您手上的问题与导入路径无关,您应提供有关问题的更多信息。

解决此问题的更好(且更永久)的方法是设置PYTHONPATH,它为解释器提供了用于python包/模块的其他目录。将PYTHONPATH编辑或设置为全局变量是os依赖的,这里将在UnixWindows上进行详细讨论。

This issue arises due to the ways in which the command line IPython interpreter uses your current path vs. the way a separate process does (be it an IPython notebook, external process, etc). IPython will look for modules to import that are not only found in your sys.path, but also on your current working directory. When starting an interpreter from the command line, the current directory you’re operating in is the same one you started ipython in. If you run

import os
os.getcwd() 

you’ll see this is true.

However, let’s say you’re using an ipython notebook, run os.getcwd() and your current working directory is instead the folder in which you told the notebook to operate from in your ipython_notebook_config.py file (typically using the c.NotebookManager.notebook_dir setting).

The solution is to provide the python interpreter with the path-to-your-module. The simplest solution is to append that path to your sys.path list. In your notebook, first try:

import sys
sys.path.append('my/path/to/module/folder')

import module-of-interest

If that doesn’t work, you’ve got a different problem on your hands unrelated to path-to-import and you should provide more info about your problem.

The better (and more permanent) way to solve this is to set your PYTHONPATH, which provides the interpreter with additional directories look in for python packages/modules. Editing or setting the PYTHONPATH as a global var is os dependent, and is discussed in detail here for Unix or Windows.


回答 1

__init__.py运行python项目时,只需在显示错误的文件夹下创建一个名称为空的python文件即可。

Just create an empty python file with the name __init__.py under the folder which showing error, while you running the python project.


回答 2

确保它们都使用相同的解释器。这在Ubuntu上发生在我身上:

$ ipython3 -c 'import sys; print(sys.version)'
3.4.2 (default, Jun 19 2015, 11:34:49) \n[GCC 4.9.1]

$ python3 -c 'import sys; print(sys.version)'
3.3.0 (default, Nov 27 2012, 12:11:06) \n[GCC 4.6.3]

而且sys.path是两个解释不同。为了解决这个问题,我删除了Python 3.3。

Make sure they are both using the same interpreter. This happened to me on Ubuntu:

$ ipython3 -c 'import sys; print(sys.version)'
3.4.2 (default, Jun 19 2015, 11:34:49) \n[GCC 4.9.1]

$ python3 -c 'import sys; print(sys.version)'
3.3.0 (default, Nov 27 2012, 12:11:06) \n[GCC 4.6.3]

And sys.path was different between the two interpreters. To fix it, I removed Python 3.3.


回答 3

主要原因是Python和IPython的sys.paths不同。

请参考lucypark链接,该解决方案适用于我的情况。它通过安装opencv时发生

conda install opencv

在iPython中出现导入错误,有三个步骤可以解决此问题:

import cv2
ImportError: ...

1.使用以下命令检查Python和iPython中的路径

import sys
sys.path

您会发现与Python和Jupyter不同的结果。第二步,只需使用sys.path.append 尝试错误即可修复错过的路径。

2.临时解决方案

在iPython中:

import sys
sys.path.append('/home/osboxes/miniconda2/lib/python2.7/site-packages')
import cv2

ImportError:..问题的解决

3.永久解决方案

创建一个iPython配置文件并设置初始追加:

在bash shell中:

ipython profile create
... CHECK the path prompted , and edit the prompted config file like my case
vi /home/osboxes/.ipython/profile_default/ipython_kernel_config.py

在vi中,附加到文件:

c.InteractiveShellApp.exec_lines = [
 'import sys; sys.path.append("/home/osboxes/miniconda2/lib/python2.7/site-packages")'
]

完成

The main reason is the sys.paths of Python and IPython are different.

Please refer to lucypark link, the solution works in my case. It happen when install opencv by

conda install opencv

And got import error in iPython, There are three steps to solve this issue:

import cv2
ImportError: ...

1. Check path in Python and iPython with following command

import sys
sys.path

You will find different result from Python and Jupyter. Second step, just use sys.path.append to fix the missed path by try-and-error.

2. Temporary solution

In iPython:

import sys
sys.path.append('/home/osboxes/miniconda2/lib/python2.7/site-packages')
import cv2

the ImportError:.. issue solved

3. Permanent solution

Create an iPython profile and set initial append:

In bash shell:

ipython profile create
... CHECK the path prompted , and edit the prompted config file like my case
vi /home/osboxes/.ipython/profile_default/ipython_kernel_config.py

In vi, append to the file:

c.InteractiveShellApp.exec_lines = [
 'import sys; sys.path.append("/home/osboxes/miniconda2/lib/python2.7/site-packages")'
]

DONE


回答 4

这样做是sys.path.append('my-path-to-module-folder')可行的,但是为了避免每次要使用IMod时都必须在IPython中执行此操作,可以将其添加export PYTHONPATH="my-path-to-module-folder:$PYTHONPATH"~/.bash_profile文件中。

Doing sys.path.append('my-path-to-module-folder') will work, but to avoid having to do this in IPython every time you want to use the module, you can add export PYTHONPATH="my-path-to-module-folder:$PYTHONPATH" to your ~/.bash_profile file.


回答 5

在安装ipython之前,我通过easy_install安装了模块;说sudo easy_install mechanize

安装ipython之后,我必须重新运行easy_install才能使ipython识别模块。

Before installing ipython, I installed modules through easy_install; say sudo easy_install mechanize.

After installing ipython, I had to re-run easy_install for ipython to recognize the modules.


回答 6

遇到了类似的问题,通过调用python3而不是python进行了修复,我的模块在Python3.5中。

Had a similar problem, fixed it by calling python3 instead of python, my modules were in Python3.5.


回答 7

如果从命令行运行它,有时python解释器将不知道在何处查找模块。

下面是我的项目的目录结构:

/project/apps/..
/project/tests/..

我在以下命令下运行:

>> cd project

>> python tests/my_test.py

运行以上命令后,出现以下错误

no module named lib

lib已导入my_test.py

我打印了sys.path并发现我正在处理的项目的路径在sys.path列表中不可用

我在脚本的开头添加了以下代码my_test.py

import sys
import os

module_path = os.path.abspath(os.getcwd())    

if module_path not in sys.path:       

    sys.path.append(module_path)

我不确定这是否是解决问题的好方法,但是是的,它确实对我有用。

If you are running it from command line, sometimes python interpreter is not aware of the path where to look for modules.

Below is the directory structure of my project:

/project/apps/..
/project/tests/..

I was running below command:

>> cd project

>> python tests/my_test.py

After running above command i got below error

no module named lib

lib was imported in my_test.py

i printed sys.path and figured out that path of project i am working on is not available in sys.path list

i added below code at the start of my script my_test.py .

import sys
import os

module_path = os.path.abspath(os.getcwd())    

if module_path not in sys.path:       

    sys.path.append(module_path)

I am not sure if it is a good way of solving it but yeah it did work for me.


回答 8

这是我解决的方法:

import os
import sys
module_path = os.path.abspath(os.getcwd() + '\\..')
if module_path not in sys.path:
    sys.path.append(module_path)

This is how I fixed it:

import os
import sys
module_path = os.path.abspath(os.getcwd() + '\\..')
if module_path not in sys.path:
    sys.path.append(module_path)

回答 9

我发现此问题的解决方案已在此处广泛记录:

https://jakevdp.github.io/blog/2017/12/05/installing-python-packages-from-jupyter/

基本上,您必须在Jupyter环境中安装软件包,并发出如下shell命令:

!{sys.executable} -m pip install numpy

请检查上面的链接以获得权威的完整答案。

I have found that the solution to this problem was extensively documented here:

https://jakevdp.github.io/blog/2017/12/05/installing-python-packages-from-jupyter/

Basically, you must install the packages within the Jupyter environment, issuing shell commands like:

!{sys.executable} -m pip install numpy

Please check the above link for an authoritative full answer.


回答 10

我发现了这种差异的另一个来源:

我在本地和在virtualenvs中都安装了ipython。我的问题是,在使用ipython新建的virtualenv内部,安装了ipython系统,它与virtualenv中的python和ipython版本不同(2.7.x与3.5.x),并且随之而来。

我认为,每当安装将要安装二进制文件的东西时,明智的做法yourvirtualenv/binrehash针对正在使用的任何外壳程序立即运行或类似运行,以便获取正确的python / ipython。(必须检查是否有合适pip的安装后挂钩…)

I found yet another source of this discrepancy:

I have ipython installed both locally and in commonly in virtualenvs. My problem was that, inside a newly made virtualenv with ipython, the system ipython was picked up, which was a different version than the python and ipython in the virtualenv (a 2.7.x vs. a 3.5.x), and hilarity ensued.

I think the smart thing to do whenever installing something that will have a binary in yourvirtualenv/bin is to immediately run rehash or similar for whatever shell you are using so that the correct python/ipython gets picked up. (Gotta check if there are suitable pip post-install hooks…)


回答 11

不带脚本的解决方案:

  1. 打开Spyder->工具-> PYTHONPATH管理器
  2. 通过单击“添加路径”来添加Python路径。例如:“ C:\ Users \ User \ AppData \ Local \ Programs \ Python \ Python37 \ Lib \ site-packages”
  3. 单击“同步…”以允许其他程序(例如Jupyter Notebook)使用在步骤2中设置的pythonpaths。
  4. 如果Jupyter已打开,请重新启动

Solution without scripting:

  1. Open Spyder -> Tools -> PYTHONPATH manager
  2. Add Python paths by clicking “Add Path”. E.g: ‘C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\site-packages’
  3. Click “Synchronize…” to allow other programs (e.g. Jupyter Notebook) use the pythonpaths set in step 2.
  4. Restart Jupyter if it is open

回答 12

这可能是由系统上安装的不同python版本(即python2python3)引起的

运行命令$ pip --version$ pip3 --version检查哪个来自Python 3x。例如,您应该看到如下版本信息:

pip 19.0.3 from /usr/local/lib/python3.7/site-packages/pip (python 3.7)

然后example.py使用以下命令运行脚本

$ python3 example.py

This is probably caused by different python versions installed on your system, i.e. python2 or python3.

Run command $ pip --version and $ pip3 --version to check which pip is from at Python 3x. E.g. you should see version information like below:

pip 19.0.3 from /usr/local/lib/python3.7/site-packages/pip (python 3.7)

Then run the example.py script with below command

$ python3 example.py

回答 13

出现在我的目录下utils。我试图将此目录导入为:

from utils import somefile

utils已经是python中的软件包。只需将您的目录名称更改为其他名称,它就可以正常工作。

Happened to me with the directory utils. I was trying to import this directory as:

from utils import somefile

utils is already a package in python. Just change your directory name to something different and it should work just fine.


回答 14

此类错误最有可能是由于python版本冲突引起的。例如,如果您的应用程序仅在python 3上运行,并且您还获得了python 2,那么最好指定要使用的版本。例如使用

python3 .....

代替

python

This kind of errors occurs most probably due to python version conflicts. For example, if your application runs only on python 3 and you got python 2 as well, then it’s better to specify which version to use. For example use

python3 .....

instead of

python

回答 15

该答案适用于此问题,如果

  1. 您不想更改代码
  2. 您不想永久更改PYTHONPATH

临时修改PYTHONPATH

下面的路径可以是相对的

PYTHONPATH=/path/to/dir python script.py

This answer applies to this question if

  1. You don’t want to change your code
  2. You don’t want to change PYTHONPATH permanently

Temporarily modify PYTHONPATH

path below can be relative

PYTHONPATH=/path/to/dir python script.py

回答 16

导入sys sys.path.append(’/ Users / {user} /Library/Python/3.7/lib/python/site-packages’)import ta

import sys sys.path.append(‘/Users/{user}/Library/Python/3.7/lib/python/site-packages’) import ta


回答 17

删除pathlib并重新安装它。删除sitepackages文件夹中的pathlib并使用pip命令重新安装pathlib软件包:

pip install pathlib

Remove pathlib and reinstall it. Delete the pathlib in sitepackages folder and reinstall the pathlib package by using pip command:

pip install pathlib