使用VSCode内置终端执行python脚本时出现OMP: Error #15错误

2023-11-08

本问题出现的必要条件

  1. Windows11 21H2
  2. 使用VSCode内置终端执行脚本,且通过编辑器右键的“在终端中运行python文件”选项启动终端
  3. 脚本中调用了matplot
  4. VSCode和Powershell都针对Conda进行了配置,Python运行在conda环境中

错误提示全文如下:

OMP: Error #15: Initializing libiomp5md.dll, but found libiomp5md.dll already initialized.
OMP: Hint This means that multiple copies of the OpenMP runtime have been linked into the program. 

That is dangerous, since it can degrade performance or cause incorrect results. 
The best thing to do is to ensure that only a single OpenMP runtime is linked into the process, 
e.g. by avoiding static linking of the OpenMP runtime in any library. 

As an unsafe, unsupported, undocumented workaround you can set the environment variable 
KMP_DUPLICATE_LIB_OK=TRUE to allow the program to continue to execute, 
but that may cause crashes or silently produce incorrect results. 

For more information, please see http://www.intel.com/software/products/support/.
ERROR conda.cli.main_run:execute(41): `conda run python <当前脚本的绝对路径>` failed. 
(See above for error)

问题的原因猜测

matpolt包调用时初始化了libiomp5md.dll文件,但是此dll会在conda激活环境时被初始化。故在python内部执行导入指令时,检测到了对这个DLL文件的两次重复加载,而这是不被允许的。
(这里是猜测,若有误请指出!我并不是很清楚OpenMP的运作逻辑)

在VSCode编辑器中,通过右键菜单直接将脚本在终端中启动时,会先执行内置终端的初始化。
默认情况下,这一次终端初始化过程会直接激活目标conda环境。
而后,VSCode会给终端注入一条指令,如下:
conda run -n pytorch --no-capture-output --live-stream python <当前脚本的绝对路径>
注意:注入指令之前,conda已经被激活,已经加载了一次上述的DLL文件。

解决方法

在VSCode的配置文件settings.json中,添加一行,如下

"python.terminal.activateEnvironment": false

意为:禁止Python内置终端在启动时自动激活conda环境

如此一来,执行脚本时,VSCode给终端注入的指令就会在基本的Powershell状态下执行,而不是在conda环境内执行。

题外话

如果想要正常启动一个PowerShell终端(而非使用VSCode内置的),而且不想Conda被自动激活,则可以在conda环境下执行指令:

conda config --set auto_activate_base false
本文的解决方法受到了下面这篇文章的启发,非常感谢!

https://blog.csdn.net/Edisonleeee/article/details/90725318

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用VSCode内置终端执行python脚本时出现OMP: Error #15错误 的相关文章

随机推荐