且构网

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

“导入错误:未命名模块"尝试运行 Python 脚本时

更新时间:2022-12-07 08:16:54

出现此问题的原因是命令行 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 编辑或设置为全局变量取决于操作系统,此处详细讨论 Unix窗口.

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.