本文介绍了VS Code Python交互式窗口ImportError:无法导入名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Anaconda环境(使用Python 3.7.4)在VS Code Python交互式窗口中运行Python脚本).我的笔记本文件根目录"设置设置为$(workspaceFolder).

I am running a Python script in the VS Code Python Interactive Window with an Anaconda environment using Python 3.7.4). My "Notebook File Root" setting is set to $(workspaceFolder).

我正在使用带有两个项目文件夹的工作区:

I am using a workspace with two project folders:

  1. 苹果
  2. 康妮

康妮有几个与此问题相关的文件:

connie has a couple of files relevant in this problem:

connie/scripts/mongo_helpers.py

connie/scripts/mongo_helpers.py

connie/project/project_file.py

connie/project/project_file.py

当我在Python交互式窗口中运行project_file.py时,会出现问题.它将尝试将mongo_helpers文件作为模块加载.

The problem occurs when I run project_file.py in the Python Interactive Window. It tries to load the mongo_helpers file as a module.

from scripts import mongo_helpers
ImportError                               Traceback (most recent call last)
c:\cygwin64\home\Robert\connie\project\project_file.py in
----> 1 from scripts import mongo_helpers

ImportError: cannot import name 'mongo_helpers' from 'scripts' (C:\Users\Robert\Anaconda3\envs\connie\lib\site-packages\scripts\__init__.py)

我打印工作目录以查看我是否在错误的文件夹中,但是看起来不错.

I print the working directory to see if I'm in the wrong folder, but it looks fine.

pwd

'c:\\cygwin64\\home\\Robert\\connie'

那为什么不能从同一根目录中的另一个文件夹导入文件?

So why can't I import a file from another folder in the same root directory?

推荐答案

问题似乎出在脚本"文件夹不在sys.path中.

The problem seems to have been that the folder 'scripts' was not on the sys.path

有关详细信息,请参见本文: https://bic-berkeley.github.io/psych-214-fall-2016/sys_path.html

See this article for details: https://bic-berkeley.github.io/psych-214-fall-2016/sys_path.html

以下代码解决了这个问题:

The following code solves the problem:

import os, sys
sys.path.append('scripts')
print(sys.path)

现在,我可以运行 import mongo_helpers 来运行mongo_helpers.py

Now I can run import mongo_helpers to run the code in mongo_helpers.py

这篇关于VS Code Python交互式窗口ImportError:无法导入名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 18:15
查看更多