首页 > 解决方案 > 导入 Python 包时出错(例如 Numpy)

问题描述

我正在使用计算集群,但无权访问整个集群。因此,我试图在本地(在我的“主”目录中)为 python 安装包,但是我在从脚本中导入它们时遇到了问题。

我尝试更新我的 PATH 和我的 PYTHONPATH,将两者都设置为 ~/.local/lib。我正在导入的集群上已经创建了一个 python 3.7.3 模块。但是我无权访问它来添加更多的包,这就是我必须在本地安装的原因。模块的路径和我的 .local 目录都在 PATH 中。

当我使用 pip 安装软件包时,出现此错误:“错误:由于 EnvironmentError 无法安装软件包:[Errno 13] Permission denied: '/s1/opt/python-3.7.3/lib/python3.7/ site-packages/numpy' 考虑使用该--user选项或检查权限。” 因此,我必须在本地安装它。当我使用该--user选项时,一切似乎都安装得很好。另外,我的.local目录下的python3.7版本只有python和site-packages目录,而集群模块中的python3.7还有很多其他文件。

安装这些软件包后,当我转到我的脚本并尝试运行它们时,我得到了这些错误。

Traceback (most recent call last):
  File "fragment_assignment.py", line 10, in <module>
    import numpy as np
  File "/s1/snagaraj/.local/lib/python3.7/site-packages/numpy/__init__.py", line 142, in <module>
    from . import core
  File "/s1/snagaraj/.local/lib/python3.7/site-packages/numpy/core/__init__.py", line 71, in <module>
    raise ImportError(msg)
ImportError: 

IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!

Importing the multiarray numpy extension module failed.  Most
likely you are trying to import a failed build of numpy.
Here is how to proceed:
- If you're working with a numpy git repository, try `git clean -xdf`
  (removes all files not under version control) and rebuild numpy.
- If you are simply trying to use the numpy version that you have installed:
  your installation is broken - please reinstall numpy.
- If you have already reinstalled and that did not fix the problem, then:
  1. Check that you are using the Python you expect (you're using /usr/bin/python),
     and that you have no directories in your PATH or PYTHONPATH that can
     interfere with the Python and numpy versions you're trying to use.
  2. If (1) looks fine, you can open a new issue at
     https://github.com/numpy/numpy/issues.  Please include details on:
     - how you installed Python
     - how you installed numpy
     - your operating system
     - whether or not you have multiple versions of Python installed
     - if you built from source, your compiler versions and ideally a build log

     Note: this error has many possible causes, so please don't comment on
     an existing issue about this - open a new one instead.

原来的错误是:

没有名为 _multiarray_umath 的模块

作为旁注,向其他有我发现的错误的人提出的所有修复对我都不起作用。

标签: python-3.xnumpy

解决方案


我建议为您的应用程序/开发需求创建一个虚拟环境,然后在其中运行。一般来说,虚拟环境是确保您拥有所需的所有依赖项并且不会与其他事物产生大量冲突问题的好方法。可能最简单的方法是使用pipenv. 关于虚拟环境和 pipenv 的另一篇文章

首先,确保pipenv已安装:

$ pip install --user pipenv

为您的项目创建一个文件夹并将目录更改为其中(或仅更改cd为您当前的项目目录):

$ mkdir my_project
$ cd my_project

my_project然后开始从您的目录中安装您需要的软件包:

$ pipenv install numpy scipy pandas

或您需要的任何软件包。该操作完成后,您可以通过运行以下命令激活您的环境:

$ pipenv shell

然后你想用python做什么。或者,您可以在环境中运行一个脚本(我们称之为my_script.py):

$ pipenv run python my_script.py

推荐阅读