vscode import error for python module

后端 未结 9 1911
栀梦
栀梦 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:06

    Thanks Honza Kalfus jankalfus

    I have noticed that if I use File -> Close folder and then File -> Open Folder... and open the project folder again, the errors are gone. If I just restart VS Code instead, I keep getting the errors. I presume that some internal cache gets cleared?

    Found here https://github.com/Microsoft/vscode/issues/10391

    0 讨论(0)
  • 2020-12-02 21:09

    In your launch.json file, change env:{} to:

    "env": {"PYTHONPATH": "${workspaceRoot}"}
    
    0 讨论(0)
  • 2020-12-02 21:09

    i did nothing but to add header in the beginning

    #!/usr/bin/env python
    

    that fixed my problem... maybe it will help somebody who is new just like me

    0 讨论(0)
  • 2020-12-02 21:10

    Since this is a VScode question I could add what my answer was.

    We are running many Python Django backends in a backends folder like so:

    +projectBackends
        -oneService
        -twoService
        -threeService
    

    And so in my project folder in VScode I just opened the projectBackends folder, because this would then give me all the services underneath it all at once. Seemed clear and simple. But then all the linting gets done from the root folder which is projectBackends, and not from the root folder of each service:

    from oneService.module1 import view
    

    gave and import error, where if I put

    from projectBackends.oneService.module1 import view
    

    I got no error, but then the microservice would not work.

    So in the end I just added a folder for every microservice in my workspace like:

    +oneService
    +twoService
    +threeService
    

    Which solved all the import errors for the independant microservices

    0 讨论(0)
  • 2020-12-02 21:12

    I tried to add this in my launch.json, then it works!

    "env": {"PYTHONPATH": "${workspaceRoot}"}
    

    below is my launch.json

            "name": "Python: Current File (Integrated Terminal)",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "cwd": "${workspaceRoot}",
            "env": {"PYTHONPATH": "${workspaceRoot}"},
            "console": "integratedTerminal"
    

    wish it can help u! :)

    0 讨论(0)
  • 2020-12-02 21:13

    There are two ways. Directly put it in launch.json or use a .env file.

    All in launch.json

    launch.json

    "env": {"PYTHONPATH": "${workspaceRoot};${workspaceRoot}/modules;${workspaceRoot}/modules/somePrj/modules"}
    

    Use a .env file

    launch.json

    "envFile": "${workspaceRoot}/.env"
    

    .env

    PYTHONPATH=".;modules;/modules/somePrj/modules"
    

    The .env file way is recommended for we can choose prod.env or test.env.

    0 讨论(0)
提交回复
热议问题