且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

“ImportError:没有名为”的模块“当试图运行Python脚本时

更新时间:2023-11-18 18:53:58

出现此问题的原因是命令行IPython解释器使用当前路径的方式与方式有关一个单独的过程(无论是IPython笔记本,外部流程等)。 IPython将查找要导入的模块,这些模块不仅可以在sys.path中找到,还可以在当前工作目录中找到。当您从命令行启动解释器时,您正在操作的当前目录与您在ipython中启动的目录相同。如果您运行

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() 

你会看到这是真的。

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

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).

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

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.

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

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.