[英]Cannot set pythonpath environment variable from python
I'm trying to debug a project that has a lot of additional libraries added to PYTHONPATH at runtime before launching the python file.在启动 python 文件之前,我正在尝试调试一个在运行时向 PYTHONPATH 添加了许多附加库的项目。
I was not able to add those commands with tasks.json
file prior to debugging python file in Visual Studio code (see post Visual Studio Code unable to set env variable paths prior to debugging python file ), so I'm just adding them via an os.system("..")
command在 Visual Studio 代码中调试 python 文件之前,我无法使用
tasks.json
文件添加这些命令(请参阅帖子Visual Studio Code 无法在调试 python 文件之前设置环境变量路径),所以我只是通过添加它们os.system("..")
命令
I'm only showing 1 of the libraries added below:我只显示下面添加的 1 个库:
# Standard library imports
import os
import sys
os.system("SET PYTHONPATH=D:\\project\\calibration\\pylibrary\\camera")
# Pylibrary imports
from camera import capture
When I debug, it fails on line from camera import capture
with:当我调试时,它
from camera import capture
在线失败:
Exception has occurred: ModuleNotFoundError
No module named 'camera'
File "D:\project\main.py", line 12, in <module>
from camera.capture import capture
I also tried我也试过
os.environ['PYTHONPATH']="D:\\project\\pylibrary\\camera"
and I still get the same error os.environ['PYTHONPATH']="D:\\project\\pylibrary\\camera"
我仍然得到同样的错误
Why is it not remembering the pythonpath
while running the script?为什么在运行脚本时不记得
pythonpath
?
How else can I define the pythonpath
while running Visual Studio Code and debugging the project file?在运行 Visual Studio Code 和调试项目文件时,我还能如何定义
pythonpath
?
I know I can add the pythonpath
to env variables in windows, but it loads too many libraries and I want it to only remember the path while the python script is executed.我知道我可以将 pythonpath 添加到
pythonpath
中的 env 变量中,但是它加载了太多的库,我希望它只记住执行 python 脚本时的路径。
Thanks谢谢
Using os.system()
won't work because it starts a new cmd.exe shell and sets the env var in that shell.使用
os.system()
将不起作用,因为它会启动一个新的 cmd.exe shell 并在该 shell 中设置环境变量。 That won't affect the env vars of the python process.这不会影响 python 进程的环境变量。 Assigning to
os.environ['PYTHONPATH']
won't work because at that point your python process has already cached the value, if any, of that env var in the sys.path
variable.分配给
os.environ['PYTHONPATH']
将不起作用,因为此时您的 python 进程已经在sys.path
变量中缓存了该环境变量的值(如果有)。 The solution is to解决方案是
import sys
sys.path.append(r"D:\project\calibration\pylibrary\camera")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.