Python ImportError报错:No module named ‘numpy.core_multiarray_umath‘

news2024/10/3 6:35:40

文章目录

  • 背景
  • Import 报错
  • 是版本问题吗?
  • 删除pandas
  • 在Visual Studio中设置Python 环境
    • 为什么要在Visual Studio IDE下继续安装Python package
    • 在Visual Studio安装numpy和pandas
    • PYTHONPATH
    • Debug模式下继续报错
    • 配置Release 工程
    • 优化
    • 不便之处 1
    • 不便之处 2
    • 后续
  • 参考

背景

C++ application 工程中增加python 脚本,实现混编

Import 报错

在python脚本中import pandas,

import os
import pandas as pd

在这里插入图片描述

是版本问题吗?

参考:

  • numpy与python版本不匹配-ImportError: Unable to import required dependencies: numpy

  • Archived: Unofficial Windows Binaries for Python Extension Packages
    这篇博文中介绍的链接能看到package版本和python以及windows系统的对应关系
    在这里插入图片描述

  • 查看版本命令

C:\Windows\System32>pip show numpy
WARNING: Ignoring invalid distribution -umpy (c:\users\junjie\appdata\roaming\python\python310\site-packages)
Name: numpy
Version: 1.22.4
Summary: NumPy is the fundamental package for array computing with Python.
Home-page: https://www.numpy.org
Author: Travis E. Oliphant et al.
Author-email:
License: BSD
Location: c:\program files\python310\lib\site-packages
Requires:
Required-by: pandas


C:\Windows\System32>pip show pandas
WARNING: Ignoring invalid distribution -umpy (c:\users\junjie\appdata\roaming\python\python310\site-packages)
Name: pandas
Version: 1.4.3
Summary: Powerful data structures for data analysis, time series, and statistics
Home-page: https://pandas.pydata.org
Author: The Pandas Development Team
Author-email: pandas-dev@python.org
License: BSD-3-Clause
Location: c:\program files\python310\lib\site-packages
Requires: numpy, python-dateutil, pytz
Required-by:

删除pandas

C:\Windows\System32>pip uninstall pandas -y
WARNING: Ignoring invalid distribution -umpy (c:\users\junjie\appdata\roaming\python\python310\site-packages)
WARNING: Ignoring invalid distribution -umpy (c:\users\junjie\appdata\roaming\python\python310\site-packages)
Found existing installation: pandas 1.4.3
Uninstalling pandas-1.4.3:
  Successfully uninstalled pandas-1.4.3

此时VS Code里面提示报错:

import os
import numpy as np
import pandas as pd  #提示无法找到该module

print("PYTHONPATH:", os.environ.get('PYTHONPATH'))
print("PATH:", os.environ.get('PATH'))

print("pandas version:", pd.__version__)
print("numpy version:",np.__version__)

继续运行App程序也会出错,这一次出错很明显和之前的不同,也是没有找到pandas module.

Traceback (most recent call last):
  File "C:\Resource\Git_Source\perf_utils\perf_utils\TextParser\x64\Debug\mergePython.py", line 2, in <module>
    import pandas as pd
ModuleNotFoundError: No module named 'pandas'

但是令人意外的是,在cmd 命令模式下执行:

pip uninstall pandas -y 

并不会卸载在Visual Stuido中安装的pandas

在Visual Studio中设置Python 环境

为什么要在Visual Studio IDE下继续安装Python package

  • AI回答的内容

Good catch! Seeing an “unresolved import” error for numpy but not os in Visual Studio specifically points to a configuration issue with the IDE. A few things to check:

  1. Make sure the Python environment being used in Visual Studio has numpy installed. The VS Python environment is separate from your global Python install.
  2. Go to Tools -> Python Environments in VS and verify numpy is installed for the environment being used. If not, install it.
  3. Open the Python Environments window (View -> Other Windows -> Python Environments), right click on your environment and select “Install Python Package” and install numpy.
  4. Check that the Python environment and interpreter path are correctly configured in VS under Tools -> Python Tools -> Environment Options.
  5. Review the Python tutorial in Visual Studio to ensure Python tools, environments, and paths are set up correctly: https://learn.microsoft.com/en-us/visualstudio/python/tutorial-working-with-python-in-visual-studio-step-05-installing-packages?view=vs-2022

在Visual Studio安装numpy和pandas

在这里插入图片描述

上面提到说,VS python 的环境和全局的Python是独立的,所以在VS 环境中安装完pandas和numpy,会有如下显示:
在这里插入图片描述
我们也看到了安装pandas过程中额外安装的包

Installing collected packages: pytz, tzdata, six, python-datautil, pandas

虽然在cmd中卸载了pandas,但是在Visual Studio环境下,仍然可以查询到pandas的版本。说明之前pip install 和 uninstall和通过Visual Studio安装的package不在同一个位置
在这里插入图片描述

  • Visutal Stuido pip isntall 的安装目录:
C:\Users\Junjie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages

在这里插入图片描述

  • cmd pip install 安装的目录:
C:\Users\Junjie\AppData\Roaming\Python\Python310\site-packages

但是当我通过命令行的方式卸载pandas之后,Visual Studio并没有去它自身安装的目录下去寻找pandas, 因此报了:

ModuleNotFoundError: No module named 'pandas'

这是否说明我的工程目录设置的不对呢?我继续问了下


Yes, I have install pandas from VS IDE and uninstall the pandas from cmd side with this cmd: pip uninstall pandas -y. After this action, I think that the application will import pandas correctly from the VS IDE installed directory. But in fact, when I run the C++ application, an error occured: “import pandas as pd ModuleNotFoundError: No module named ‘pandas’” It seams that the application import the pandas from default pip install directory, but not the VS installed directory. Forget to tell the application, the app is constructed from a C++ project but not an python project. In this C++ project, I need to call PyImport_ImportModule to run python script, in which need to “Import pandas as pd” , so how do I to do next step


下面是人工智能给我的回答:


Ah I see, since this is a C++ application importing Python code, the Python environment and module import behavior will be different than just running Python code directly.

Here are a few things you can try:

  • Make sure the Python environment you have configured in Visual Studio is the same one being used by PyImport_ImportModule in your C++ code. Double check the Python interpreter path and version.
  • Set the PYTHONPATH environment variable before calling PyImport_ImportModule to include the path to the VS installed pandas module. This will override the default paths.
  • Alternatively, you can manipulate sys.path before importing pandas to prepend the VS installed site-packages dir.
  • As a test, try installing pandas globally via pip instead of in VS, and see if your C++ code picks it up from the default path.
    Consider using virtual environments to better control the Python environment, packages, and paths for your C++ project separately from any global installs.

这让我注意到在之前打印PYTHONPATH信息时,是空的

import os
print("PYTHONPATH:", os.environ.get('PYTHONPATH'))

蓝色字样中提到:

在调用 PyImport_ImportModule 之前设置 PYTHONPATH 环境变量以包含 VS 安装的 pandas 模块的路径。这将覆盖默认路径。

那么问题就转到PYTHONPATH是什么,并且如何设置

或者,您可以在导入 pandas 之前操作 sys.path 以添加 VS 安装的站点包目录。

PYTHONPATH

PYTHONPATH 是一个环境变量,您可以设置它来添加 python 将在其中查找模块和包的其他目录

print(sys.path)
sys.path.append('C:\\Users\\Junjie\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python310\\site-packages')
print(sys.path)

输出:

['C:\\Program Files\\Python310\\python310.zip', 'C:\\Program Files\\Python310\\Lib', 'C:\\Program Files\\Python310\\DLLs', 'C:\\Resource\\Git_Source\\perf_utils\\perf_utils\\TextParser\\x64\\Release', 'C:\\Users\\Junjie\\AppData\\Roaming\\Python\\Python310\\site-packages', 'C:\\Users\\Junjie\\AppData\\Roaming\\Python\\Python310\\site-packages\\win32', 'C:\\Users\\Junjie\\AppData\\Roaming\\Python\\Python310\\site-packages\\win32\\lib', 'C:\\Users\\Junjie\\AppData\\Roaming\\Python\\Python310\\site-packages\\Pythonwin', 'C:\\Program Files\\Python310', 'C:\\Program Files\\Python310\\lib\\site-packages']

['C:\\Program Files\\Python310\\python310.zip', 'C:\\Program Files\\Python310\\Lib', 'C:\\Program Files\\Python310\\DLLs', 'C:\\Resource\\Git_Source\\perf_utils\\perf_utils\\TextParser\\x64\\Release', 'C:\\Users\\Junjie\\AppData\\Roaming\\Python\\Python310\\site-packages', 'C:\\Users\\Junjie\\AppData\\Roaming\\Python\\Python310\\site-packages\\win32', 'C:\\Users\\Junjie\\AppData\\Roaming\\Python\\Python310\\site-packages\\win32\\lib', 'C:\\Users\\Junjie\\AppData\\Roaming\\Python\\Python310\\site-packages\\Pythonwin', 'C:\\Program Files\\Python310', 'C:\\Program Files\\Python310\\lib\\site-packages', 'C:\\Users\\Junjie\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python310\\site-packages']

可以看到后面的print就是多了一个‘C:\Users\Junjie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages’
这就是Visual Studio安装的package目录

Debug模式下继续报错

报错的内容和第一节一开始的内容相同,根据报错内容中的提示:
Numpy ImportError

  • Debug build on Windows
    Rather than building your project in DEBUG mode on windows, try building in RELEASE mode with debug symbols and no optimization. Full DEBUG mode on windows changes the names of the DLLs python expects to find, so if you wish to truly work in DEBUG mode you will need to recompile the entire stack of python modules you work with including NumPy

  • 建议:release模式,保留debug符号,不进行优化

    try building RELEASE mode with debug symbols and no optimization 
    

配置Release 工程

参考《Visual Studio在Release模式下开启debug调试》 配置Release模式

  • cpp
void merge_csv(string PythonModuleName, string PythonFunctionName, string csv_dir)
{
    Py_Initialize();
    
    // ... 省略
    
    PyObject *pModule = NULL;
    pModule = PyImport_ImportModule(PythonModuleName.c_str());
    if (!pModule)
    {
        PyErr_Print();
        cout << "Python import failed!" << endl;
        return;
    }
    
    //...省略

    Py_Finalize();
}

  • python
import os
import sys
print(sys.path)
sys.path.append('C:\\Users\\Junjie\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python310\\site-packages')
print(sys.path)
import pandas as pd

def merge_csv(csv_dir):
    #... 省略
    return

经过上述配置和操作后,程序能正常运行。 这些操作包括:

  • 在Visual Studio Python环境下安装package
  • 编译Release版本

优化

如果在python中添加自定义的Visual Studio 的install path,这样肯定还是不行的。因为移植给其他人用的时候,路径并不一定正确。 此时有一个想法,既然在重新配置sys.path.append()后只增加了Visual Studio的package install目录,那么如果保持pip安装的目录下,两者的版本一致,是不是也一样呢?想到这一点的原因是参考了博文:
python脚本中的sys.path.append(“…”)详解 中提到的

当我们导入一个模块时: import xxx ,默认情况下python解释器会搜索当前目录、已安装的内置模块和第三方模块。
packagepipVS IDE
numpy1.22.41.25.2
pandas1.4.32.0.3
  • 优化:
      1. 卸载掉pip 安装的numpy和pandas
      1. 安装VS 相同的版本
      1. 去掉Python 脚本中额外增加的sys.path.append(xxx)
C:\Windows\System32>pip uninstall pandas -y
C:\Windows\System32>pip uninstall numpy -y
C:\Windows\System32>pip install numpy==1.25.2
C:\Windows\System32>pip install pandas==2.0.3
C:\Windows\System32>pip show numpy
C:\Windows\System32>pip show pandas

此时程序同样能跑起来,也证明了上面的猜想~

不便之处 1

到这里,虽然实现了C++ 和 Python 的混编, 但是整个配置过程较复杂,如果是简单的python脚本,原始安装的python 目录下应该可以满足。但是如果是像pandas这类,可能会遇到版本不一致和Debug/Release模式的问题,这给调试带来了不方便之处。
当然,可以使用虚拟环境去配置C++应用开发环境,从而和global 的环境区分开来。这里暂时没有去研究了。

  • Consider using virtual environments to better control the Python environment, packages, and paths for your C++ project separately from any global installs.

不便之处 2

打包问题。在实现功能后,整个混编环境的打包也难住了我。单纯的python 脚本可以通过pyinstaller 命令打包所需要的package并生成exe可执行文件。但是这类混编的打包好像没有一个命令去实现,这对于工具类的软件不是很方便。当我share这类工具给别人使用的时候,可能需要安装一堆package才能使用。设想了下别人使用该工具时需要做的步骤:

  • 安装指定版本的python
  • 安装指定版本的package(此例中为numpy-1.25.2, pandas-2.0.3)

后续

如果想实现混编并且比较好的打包,看来得研究一下虚拟环境下的C++工程的配置了。

参考

numpy与python版本不匹配-ImportError: Unable to import required dependencies: numpy
PYTHONPATH 变量为空
Step 5: Install packages in your Python environment
Pandas 如何查找已安装的版本
Numpy Troubleshooting
visual stdio c++调用python混合编程
Visual Studio在Release模式下开启debug调试
python脚本中的sys.path.append(“…”)详解

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/864762.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Reinforcement Learning with Code【Code 5. Policy Gradient Methods】

Reinforcement Learning with Code【Code 5. Policy Gradient Methods】 This note records how the author begin to learn RL. Both theoretical understanding and code practice are presented. Many material are referenced such as ZhaoShiyu’s Mathematical Foundati…

想要延长Macbook寿命?这六个保养技巧你必须get!

Mac作为我们工作生活的伙伴&#xff0c;重要性不需要多说。但在使用的过程中&#xff0c;我们总会因不当操作导致Mac出现各种问题。 要想它长久的陪伴&#xff0c;平时的维护与保养自然不能少&#xff0c;Mac的保养很重要的两点就是硬件保养和电脑系统保养&#xff0c;硬件保养…

企业服务器中了Locked勒索病毒怎么办,勒索病毒解密有哪些步骤

随着网络技术的不断发展&#xff0c;勒索病毒攻击成为了企业面临的一种风险。近期&#xff0c;我们收到某医药公司的求助&#xff0c;企业的服务器数据库遭到了locked勒索病毒的攻击&#xff0c;导致企业服务器内的许多重要数据被加密无法正常读取&#xff0c;不仅影响到了企业…

智能合约 -- 常规漏洞分析 + 实例

1.重入攻击 漏洞分析 攻击者利用合约漏洞&#xff0c;通过fallback()或者receive()函数进行函数递归进行无限取钱。 刚才试了一下可以递归10次&#xff0c;貌似就结束了。 直接看代码: 银行合约&#xff1a;有存钱、取钱、查看账户余额等函数。攻击合约: 攻击、以及合约接…

ECG和PPG信号用于PTT、HRV和PRV研究(Matlab代码实现)

&#x1f4a5;&#x1f4a5;&#x1f49e;&#x1f49e;欢迎来到本博客❤️❤️&#x1f4a5;&#x1f4a5; &#x1f3c6;博主优势&#xff1a;&#x1f31e;&#x1f31e;&#x1f31e;博客内容尽量做到思维缜密&#xff0c;逻辑清晰&#xff0c;为了方便读者。 ⛳️座右铭&a…

微信朋友圈置顶功能已大范围上线!

微信是目前全球最受欢迎的社交媒体应用之一&#xff0c;拥有数十亿的用户。作为一款持续发展和改进的应用&#xff0c;微信不断推出新的功能来提升用户体验。 近日&#xff0c;iOS微信8.0.41内测版迎来了更新&#xff0c;本次更新距离上个正式版间隔了大概10天的时间。 微信朋友…

BI技巧丨利用Index计算半累计

在实际的业务场景中&#xff0c;特别是财务模块和库存管理模块&#xff0c;经常需要我们针对每个月的期初期末进行相关指标计算&#xff0c;这也是我们之前曾经提到的Calculate基础应用——半累计计算。 现在我们也可以通过微软新推出的Index开窗函数来解决这一问题。 INDEX函…

健启星|医学营养的市场先行者

随着《“健康中国2030”规划纲要》、《国民营养计划&#xff08;2017-2030年&#xff09;》等政策的陆续发布&#xff0c;标志着以传统药物治疗为中心的医疗模式时代正式转型到以预防和康复为中心的新的医学营养时代。在此背景下&#xff0c;符合时代需求的特医食品成为“医学营…

HbuildX生成安卓签名证书

HbuildX生成安卓签名证书 安装和配置JRE环境 根据此链接安装和配置JRE环境 生成签名证书 keytool -genkey -alias testalias -keyalg RSA -keysize 2048 -validity 36500 -keystore test.keystoretestalias是证书别名&#xff0c;可修改为自己想设置的字符&#xff0c;建议…

闻道网络:2023宠物消费网络营销洞察数据报告(附下载)

关于报告的所有内容&#xff0c;公众【营销人星球】获取下载查看 核心观点 行业持续升级&#xff0c;增速放缓&#xff0c;正朝着多元化和专业化的方向发展&#xff1b;自公共事件以来&#xff0c;因&#xff0c;“猫不用遛”&#xff0c;养猫人士增速迅猛反超犬主人&#xf…

Qt在mac安装

先在app store下载好Xcode 打开Xcode 随便建个文件 给它取个名字 找个地方放 提醒没建立git link,不用理他 打开终端&#xff0c; 输入/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" 开始安装啦 继续在终端…

MySQL中的用户管理

系列文章目录 MySQL常见的几种约束 MySQL中的函数 MySQL中的事务 MySQL中的视图 MySQL中的索引 文章目录 系列文章目录前言一、用户管理1、用户管理入门2、用户管理操作及示例 二、权限管理1.权限管理语法2.权限操作示例 三、角色管理1、角色管理入门2、角色操作示例 总结…

Chisel 语言 - 小记

文章目录 Chisel 一种硬件描述语言&#xff0c;类似 verilog 本质是 Scala编程语言的一个包&#xff0c;类似于 numpy 是 Python 的一个包。 官网 &#xff1a; https://www.chisel-lang.orggithub&#xff1a; https://github.com/chipsalliance/chisel 同名的还有个 Facebook…

【数学建模】--灰色关联分析

系统分析: 一般的抽象系统&#xff0c;如社会系统&#xff0c;经济系统&#xff0c;农业系统&#xff0c;生态系统&#xff0c;教育系统等都包含有许多种因素&#xff0c;多种因素共同作用的结果决定了该系统的发展态势。人们常常希望知道在众多的因素中&#xff0c;哪些是主要…

每天一道leetcode:516. 最长回文子序列(动态规划中等)

今日份题目&#xff1a; 给你一个字符串 s &#xff0c;找出其中最长的回文子序列&#xff0c;并返回该序列的长度。 子序列定义为&#xff1a;不改变剩余字符顺序的情况下&#xff0c;删除某些字符或者不删除任何字符形成的一个序列。 示例1 输入&#xff1a;s "bbb…

Nginx环境搭建以及Docker环境部署

目录 Nginx环境搭建 1.首先创建Nginx的目录并进入 2.下载Nginx的安装包 可以通过FTP工具上传离线环境包&#xff0c;也可通过wget命令在线获取安装包 没有wget命令的可通过yum命令安装 3.解压Nginx的压缩包 4.下载并安装Nginx所需的依赖库和包 安装方式一 安装方式二 --- 也…

hello world, this is my time

case1 2023-08-11 00:19:12 其实我这个人吧, 没事做也会刷点b站和抖音, 而且我经常看罗翔老师讲, 什么是爱, 他说爱是责任, 爱是不离不弃, 爱是有耐心, 爱是安慰, 爱也是陪伴, 爱同时也是一种共生的关系, 两个人彼此之间共生, 互相都希望彼此可以好好的生活下去, 看见对方活的比…

Git全栈体系(六)

第十章 自建代码托管平台-GitLab 一、GitLab 简介 GitLab 是由 GitLabInc.开发&#xff0c;使用 MIT 许可证的基于网络的 Git 仓库管理工具&#xff0c;且具有 wiki 和 issue 跟踪功能。使用 Git 作为代码管理工具&#xff0c;并在此基础上搭建起来的 web 服务。GitLab 由乌克…

红帽停止公开Linux操作系统(RHEL)源代码,甲骨文等企业成立协会

根据报道&#xff0c;红帽&#xff08;Red Hat&#xff09;在8月11日宣布停止公开企业级Linux操作系统&#xff08;RHEL&#xff09;的源代码后&#xff0c;甲骨文、SUSE和CIQ昨日联合发布了一份声明。声明宣布成立了Open Enterprise Linux Association&#xff08;OpenELA&…

安全测试中常见的业务安全问题

“在测试过程中&#xff0c;特殊的操作往往容易触发异常场景&#xff0c;而这些异常场景也很容易引起安全问题&#xff01;” 常见的安全漏洞就不多说了&#xff0c;这里主要介绍常见的业务安全问题及修复建议。 01 刷短信 问题描述&#xff1a; 当发送短信的请求接口只需要…