3

Here's my file structure

test/
  -dir1
    -thing.py
  -dir2
    -__init__.py
    -thing2.py

I am using python 3.7 and windows 10.

In thing.py, I'm trying to import a function called foo from thing2.py and have it execute when I run thing.py. My code works perfectly in PyCharm when I press run. However, when I run thing.py from the terminal directly or through code runner in VSCode, I get the following error:

from dir2.thing2 import foo

ERROR: ModuleNotFoundError: No module named 'dir2

Is the issue something to do with my PYTHONPATH or something else?

Aditya Mehrotra
  • 323
  • 1
  • 18
  • I'd compare the current working directory when running your script on both pycharm and on vs code. –  Jan 05 '21 at 10:48
  • Almost duplicate of [visual studio code - vscode import error for python module - Stack Overflow](https://stackoverflow.com/questions/46520127/vscode-import-error-for-python-module) (the answers there are fine, but the OP is doing manuallies is.path modification?) – user202729 Jan 06 '21 at 03:25

1 Answers1

3

Based on the information you provided, I reproduced the problem you described. And you could use the following methods to solve it:

  1. Please add the following code at the beginning of the "thing.py" file, which adds the path of the currently opened file to the system path so that VSCode can find "foo" according to "from dir2.thing2 import foo":
import os, sys 
sys.path.append('./')

enter image description here

  1. If you don't want to add code, you could add the following setting in "launch.json", which adds the path of the project when debugging the code:
 "env": {
                    "PYTHONPATH": "${workspaceFolder}"
                }

enter image description here

Jill Cheng
  • 9,179
  • 1
  • 20
  • 25