简体   繁体   English

尝试运行 Python 脚本时出现“ImportError: No module named”

[英]"ImportError: No module named" when trying to run Python script

I'm trying to run a script that launches, amongst other things, a python script.我正在尝试运行一个脚本来启动 python 脚本等。 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.我得到一个 ImportError: No module named...,但是,如果我启动 ipython 并通过解释器以相同的方式导入相同的模块,则该模块被接受。

What's going on, and how can I fix it?发生了什么事,我该如何解决? I've tried to understand how python uses PYTHONPATH but I'm thoroughly confused.我试图了解 python 如何使用 PYTHONPATH 但我完全糊涂了。 Any help would greatly appreciated.任何帮助将不胜感激。

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 解释器使用当前路径的方式与单独进程的方式(无论是 IPython 笔记本、外部进程等)的方式。 IPython will look for modules to import that are not only found in your sys.path, but also on your current working directory. IPython 将寻找不仅可以在您的 sys.path 中找到的要导入的模块,而且还可以在您当前的工作目录中找到。 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从命令行启动解释器时,您正在操作的当前目录与您启动 ipython 的目录相同。如果您运行

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

The solution is to provide the python interpreter with the path-to-your-module.解决方案是为 python 解释器提供模块路径。 The simplest solution is to append that path to your sys.path list.最简单的解决方案是将 append 该路径指向您的 sys.path 列表。 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.解决这个问题的更好(和更永久)的方法是设置你的PYTHONPATH ,它为解释器提供了额外的目录来查找 python 包/模块。 Editing or setting the PYTHONPATH as a global var is os dependent, and is discussed in detail here for Unix or Windows .将 PYTHONPATH 编辑或设置为全局变量取决于操作系统,此处针对UnixWindows进行了详细讨论。

Just create an empty python file with the name __init__.py under the folder which showing error, while you running the python project.运行 python 项目时,只需在显示错误的文件夹下创建一个名为__init__.py的空 python 文件。

Make sure they are both using the same interpreter.确保他们都使用相同的解释器。 This happened to me on Ubuntu:这在 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.两个解释器之间的sys.path是不同的。 To fix it, I removed Python 3.3.为了修复它,我删除了 Python 3.3。

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

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.执行sys.path.append('my-path-to-module-folder')将起作用,但为了避免每次要使用模块时都必须在 IPython 中执行此操作,可以添加export PYTHONPATH="my-path-to-module-folder:$PYTHONPATH"到您的~/.bash_profile文件。

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)

Before installing ipython, I installed modules through easy_install;在安装ipython之前,我通过easy_install安装了模块; say sudo easy_install mechanize .sudo easy_install mechanize

After installing ipython, I had to re-run easy_install for ipython to recognize the modules.安装 ipython 后,我不得不重新运行 easy_install 以便 ipython 识别模块。

If you are running it from command line, sometimes python interpreter is not aware of the path where to look for modules.如果您从命令行运行它,有时 python 解释器不知道查找模块的路径。

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 lib 被导入 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我打印了 sys.path 并发现我正在处理的项目路径在 sys.path 列表中不可用

i added below code at the start of my script my_test.py .我在脚本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.我不确定这是否是解决它的好方法,但它确实对我有用。

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/ 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:基本上,您必须在 Jupyter 环境中安装软件包,发出 shell 命令,例如:

 .{sys executable} -m pip install numpy

Please check the above link for an authoritative full answer.请检查上面的链接以获得权威的完整答案。

This kind of errors occurs most probably due to python version conflicts.出现这种错误很可能是由于 python 版本冲突。 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.例如,如果您的应用程序仅在 python 3 上运行并且您也获得了 python 2,那么最好指定要使用的版本。 For example use例如使用

python3.....

instead of代替

python

Had a similar problem, fixed it by calling python3 instead of python , my modules were in Python3.5.有类似的问题,通过调用python3而不是python来修复它,我的模块在 Python3.5 中。

I found yet another source of this discrepancy:我发现了这种差异的另一个来源:

I have ipython installed both locally and in commonly in virtualenvs.我在本地和通常在 virtualenvs 中都安装了 ipython。 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.我的问题是,在一个新制作的带有 ipython 的 virtualenv 中,系统 ipython 被拾取,它与 virtualenv 中的 python 和 ipython 不同版本(2.7.x 与 3.5.x),然后欢闹。

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.我认为,每当安装将在yourvirtualenv/bin中包含二进制文件的东西时,明智的做法是立即对您正在使用的任何 shell 运行rehash或类似操作,以便获取正确的 python/ipython。 (Gotta check if there are suitable pip post-install hooks...) (要检查是否有合适的pip安装后挂钩...)

Solution without scripting:没有脚本的解决方案:

  1. Open Spyder -> Tools -> PYTHONPATH manager打开 Spyder -> 工具 -> PYTHONPATH 管理器
  2. Add Python paths by clicking "Add Path".通过单击“添加路径”添加 Python 路径。 Eg: 'C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\site-packages'例如:'C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\site-packages'
  3. Click "Synchronize..." to allow other programs (eg Jupyter Notebook) use the pythonpaths set in step 2.单击“同步...”以允许其他程序(例如 Jupyter Notebook)使用在步骤 2 中设置的 pythonpaths。
  4. Restart Jupyter if it is open如果 Jupyter 已打开,请重新启动它

This is probably caused by different python versions installed on your system , ie python2 or python3 .这可能是由于您的系统上安装了不同的 python 版本,即python2python3造成的。

Run command $ pip --version and $ pip3 --version to check which pip is from at Python 3x .运行命令$ pip --version$ pip3 --version检查哪个pip来自Python 3x Eg 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然后使用以下命令运行example.py脚本

$ python3 example.py

Happened to me with the directory utils .目录utils发生在我身上。 I was trying to import this directory as:我试图将此目录导入为:

 from utils import somefile

utils is already a package in python. utils已经是 python 中的 package。 Just change your directory name to something different and it should work just fine.只需将您的目录名称更改为不同的名称,它应该可以正常工作。

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您不想永久更改 PYTHONPATH

Temporarily modify PYTHONPATH 临时修改 PYTHONPATH

path below can be relative下面的路径可以是相对的

PYTHONPATH=/path/to/dir python script.py
 import sys sys.path.append('/Users/{user}/Library/Python/3.7/lib/python/site-packages') import ta

If anyone comes across this issue using conda with Jupyter Notebook in MSVS Code, the solution is to make sure you're using the correct kernel.如果有人在 MSVS 代码中使用带有conda Notebook 的 conda 遇到此问题,解决方案是确保您使用正确的 kernel。 The kernel is in a box in the top right corner of the interface and looks like this: kernel 在界面右上角的一个方框中,如下所示:

在此处输入图像描述

I pointed mine to the version of Python that also matched my application path -- problem solved我指出我的 Python 版本也与我的应用程序路径匹配——问题已解决

This problem occurs due to the different versioning - eg if the Python installed on your machine is installed in a folder called path_to_lib/python3.6 but your notebook is running in Python 3 - the spacing in the naming matters出现此问题是由于版本不同 - 例如,如果您机器上安装的 Python 安装在名为path_to_lib/python3.6的文件夹中,但您的笔记本运行在Python 3 - 命名中的间距很重要

How to solve it?如何解决?

When creating a new jupyter notebook, just choose the Python with the same versioning as yours (watch out for spaces.).创建新的 jupyter notebook 时,只需选择与您的版本相同的 Python(注意空格。)。 See the attached image见附图

选择正确的 Python 版本控制

This is what worked for me: I just changed my working directory inside my notebook这对我有用:我刚刚更改了笔记本中的工作目录

import os os.chdir("my/path/to/module") os.getcwd()

I have a similar issued with my Jupyter Lab setup which I resolved by checking the Jupyter Lab log on opening.我的 Jupyter Lab 设置也有类似问题,我通过检查 Jupyter Lab 打开时的日志解决了这个问题。 This informed me that the virtual environment (pipenv) couldn't locate the Jupyter Lab so it used a shared version (from an earlier installation of Python).这告诉我虚拟环境 (pipenv) 无法找到 Jupyter Lab,因此它使用了共享版本(来自早期安装的 Python)。

I created a requirements.txt and discovered I hadn't installed Jupyter Lab in this new environment.我创建了一个 requirements.txt,发现我没有在这个新环境中安装 Jupyter Lab。 Installing it resolved the import error.安装它解决了导入错误。

Remove pathlib and reinstall it.删除pathlib并重新安装它。 Delete the pathlib in sitepackages folder and reinstall the pathlib package by using pip command:删除sitepackages文件夹中的 pathlib 并使用 pip 命令重新安装 pathlib package:

 pip install pathlib

暂无
暂无

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

相关问题 尝试从 ssm 运行 ec2 python 脚本时出现“ImportError: No module named sqlalchemy”错误 - 'ImportError: No module named sqlalchemy' error when trying to run ec2 python script from ssm 尝试使用Python 3运行Flask时出现“ ImportError:没有名为SocketServer的模块” - “ImportError: No module named SocketServer” when trying to run Flask with Python 3 尝试运行在OS X上利用scapy的脚本时,'ImportError:没有名为dumbnet的模块' - 'ImportError: No module named dumbnet' when trying to run a script that leverages scapy on OS X python运行ImportError:没有命名模块 - python run ImportError:No module named 无法运行 python 脚本 - 导入错误:没有名为“_chipset”的模块 - Cannot run python script - ImportError: No module named '_chipset' 尝试通过解释器运行Python脚本时,为什么会出现“ ImportError:未命名模块”的提示? - Why do I get “ImportError: No module named” when I try to run my Python script via the Interpreter? ImportError:在Raspberry Pi上运行python脚本时,没有名为“ azure”的模块 - ImportError: No module named 'azure' when running python script on Raspberry Pi 在crontab中运行python脚本时出现“ ImportError:没有名为praw的模块”错误 - “ImportError: No module named praw” error when running python script in crontab crontab Python 脚本中的“ImportError: No module named requests” - “ImportError: No module named requests” in crontab Python script ModuleNotFoundError:尝试从 Excel 中的 VBA 宏运行 Python 脚本时,没有名为“xlwings”的模块 - ModuleNotFoundError: No module named 'xlwings' when trying to run a Python script out of a VBA macro in Excel
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM