VS Code Python Interactive Window ImportError: cannot import name

为君一笑 提交于 2021-01-29 12:52:44

问题


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. apple
  2. connie

connie has a couple of files relevant in this problem:

connie/scripts/mongo_helpers.py

connie/project/project_file.py

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?


回答1:


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

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)

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



来源:https://stackoverflow.com/questions/59782772/vs-code-python-interactive-window-importerror-cannot-import-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!