shirocheng
V2EX  ›  问与答

vscode Python 的提示与实际运行的路径冲突?

  •  
  •   shirocheng · Oct 27, 2019 · 4159 views
    This topic created in 2568 days ago, the information mentioned may be changed or developed.

    如图,希望在二级文件夹下的 main.py 中导入同一文件夹下的 DHash.py 中定义的类

    vscode 提示的路径是相对工作区,而不是相对当前文件的

    而 Python 文件运行时是以当前文件为相对路径的,运行 main.py 出错: ModuleNotFoundError: No module named 'image_compare'

    需要这样写才行:

    求教:如何修复 vscode python 的路径提示?

    12 replies  •  2019-12-06 10:49:16 +08:00
    renmu
    renmu
    Oct 27, 2019 via Android
    1
    加一个__init__. py
    yaming116
    yaming116
    Oct 27, 2019 via iPhone
    2
    @renmu 然而并不是,项目放到 pycham 运行好好的,已经添加了__init__,不知道为啥不行,暂时放弃了
    ipwx
    ipwx
    Oct 27, 2019 via Android
    3
    @yaming116 pycharm 自动帮你设置了 pythonpath 环境变量。剩下的请谷歌
    shirocheng
    shirocheng
    OP
    Oct 27, 2019
    4
    @yaming116
    是的,在 pycharm 上就没问题...奈何 vscode 比较轻量,还是想用 vscode 😂
    Trim21
    Trim21
    Oct 27, 2019 via iPhone
    5
    你把终端的 pwd 放到工作区去运行 main.py 应该就行了

    或者手动指定 pythonpath,在设置项里搜一搜,设置到工作区设置里
    CallMeReznov
    CallMeReznov
    Oct 28, 2019
    6
    你 vscode 里 python 插件安装后你设置 python 的路径没?
    linvaux
    linvaux
    Oct 28, 2019 via Android
    7
    set PYTHONPATH=$(pwd)
    shirocheng
    shirocheng
    OP
    Oct 28, 2019
    8
    @Trim21
    是的,以工作区打开就没问题了。。。
    请问 PythonPath 是指运行 Python 的路径吗,我的设置为:/usr/local/Caskroom/miniconda/base/envs/OpenCV/bin/python
    Trim21
    Trim21
    Oct 28, 2019 via iPhone
    9
    不是,你自己搜一下吧
    shirocheng
    shirocheng
    OP
    Oct 28, 2019
    10
    @Trim21
    嗯,终于在 issues 里搜到了。
    是在 python.envFile 对应的配置文件中,加上 PYTHONPATH=codeFolder 对吗?
    这样可以正确在对应目录下分析导入包了,不过不像 pycharm 会自动设置 PYTHONPATH,稍微有点不便
    shirocheng
    shirocheng
    OP
    Dec 6, 2019 via iPhone
    12
    https://segmentfault.com/a/1190000021046003
    vscode 文档中给出了很方便的解决方案,配置中添加需要解析的文件夹即可
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1489 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 06:11 · PVG 14:11 · LAX 22:11 · JFK 01:11
    ♥ Do have faith in what you're doing.