vscode import error for python module

后端 未结 9 1958
栀梦
栀梦 2020-12-02 20:26

I am trying to do an import in python from one directory level up.

import sys

sys.path.append(\'..\')
from cn_modules import exception

I g

9条回答
  •  温柔的废话
    2020-12-02 21:20

    I have had the same problem, in my case it was caused by the current directory of the vscode debug process being different to the directory the script was in. It is helpful to do a

    print('cwd is %s' %(os.getcwd()))
    

    Just before your sys.path.append and your imports. What happened with me is that the running environment cwd seems to default to the workspace directory, which seems to be the directory containing the vs code project file, and if this is not where your script is located, then your relative include paths are broken.

    A solution to this is to insure that your script changes its current directory to the directory where the script is located, and also to append your syspath to the directory where the script is located:

    scriptdir = os.path.dirname(os.path.realpath(__file__))
    print('dir containing script is %s' % (scriptdir))
    
    # append our extra module directory (in this case Autogen) onto the script directory
    
    sys.path.append(os.path.join(scriptdir, 'Autogen'))
    
    # also change cwd to where the script is located (helps for finding relative files)
    print('============\ncwd is %s' %(os.getcwd()))
    
    os.chdir(scriptdir)
    print('============\ncwd after change to script dir is %s' %(os.getcwd()))
    

    All the above steps will help to make your script run well, but they will not help for intellisense or code completion. To have the code completion run well, you must create a .env file (usually in the same directory as your .vscode directory) and in your .env file you add the directories where you want vscode to look for extra python modules

    Contents of .env file

    PYTHONPATH="someDirRelativeTowhereYourVSCodeProjectLives\\Autogen"
    

提交回复
热议问题