问题
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:
- apple
- 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