ModuleNotFoundError: Модуль без имени ... только для некоторых пакетов - PullRequest
1 голос
/ 08 мая 2019

Я использую Portable Msys2 под Win 10. Я установил Python 3.7 и 2.7.

Я нахожу ошибки при импорте только некоторых пакетов . Я думаю, мне нужно найти правильную настройку PYTHONPATH, но пока я не смог.

Все это было вызвано ошибкой, полученной при импорте numpy (указано ниже). Затем я обнаружил другие «похожие», но не равные ошибки, и я не уверен, что они имеют один и тот же источник.

Для справки:

$ env | grep -i python
PYTHONSTARTUP=/home/user1/.pythonrc
PYTHONPATH=( I will list options I tried below )

и мой .pythonrc указан внизу.

Пары каталогов, релевантные для импорта, выглядят так:

  1. Пара usr и usr_sp: C:\Users\user1\Documents\appls_mydocs\PortableApps\MSYS2Portable\App\msys32\usr\lib\python3.7\
    C:\Users\user1\Documents\appls_mydocs\PortableApps\MSYS2Portable\App\msys32\usr\lib\python3.7\site-packages

  2. Пара mingw64 и mingw64_sp: C:\Users\user1\Documents\appls_mydocs\PortableApps\MSYS2Portable\App\msys32\mingw64\lib\python3.7\
    C:\Users\user1\Documents\appls_mydocs\PortableApps\MSYS2Portable\App\msys32\mingw64\lib\python3.7\site-packages

Для каждой опции PYTHONPATH я пытался импортировать (возможно вслепую) модули и пакеты, которые присутствуют только в той или иной паре каталогов.

  1. в паре mingw64, а не в паре usr:
    msilib является единственным пакетом, представленным в mingw64, которого нет в usr. В mingw64 отсутствуют модули, отсутствующие в usr.
    cairo, colorama и numpy входят в число многих пакетов, представленных в mingw64_sp, которых нет в usr_sp. pytest - это один модуль, присутствующий в mingw64_sp, который не находится в usr_sp.

  2. В паре usr, а не в паре mingw64:
    В usr нет пакетов, которых нет в mingw64. В usr отсутствуют модули, отсутствующие в mingw64.
    pip - единственный пакет, присутствующий в usr_sp, который не входит в mingw64_sp. magic - единственный модуль, присутствующий в usr_sp, которого нет в mingw64_sp.

Варианты, которые я пробовал:

  1. Ничего в PYTHONPATH. Результаты ниже ( tl; dr ) предполагают, что usr и usr_sp найдены, а mingw64 и mingw64_sp нет.


    ТЛ; др
    [~]$ unset PYTHONPATH
    [~]$ python3
    Python 3.7.2 (default, Dec 26 2018, 08:23:20)
    [GCC 7.4.0] on msys
    Type "help", "copyright", "credits" or "license" for more information.
    Reading /home/user1/.pythonrc
    readline is in /usr/lib/python3.7/lib-dynload/readline.cpython-37m.dll
    >>> import sys
    >>> sys.path
    ['', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/usr/lib/python3.7/site-packages']
    >>> import datetime
    >>> import json
    >>> import msilib
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ModuleNotFoundError: No module named 'msilib'
    >>> import cairo
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ModuleNotFoundError: No module named 'cairo'
    >>> import colorama
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ModuleNotFoundError: No module named 'colorama'
    >>> import pip
    >>> import pytest
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ModuleNotFoundError: No module named 'pytest'
    >>> import magic
    >>> exit()
    

  2. PYTHONPATH с добавленной парой mingw64. Результаты ниже ( tl; dr ) показывают, что обе пары (usr, usr_sp) и (mingw64, mingw64_sp) найдены. Но что-то все еще не хватает только для некоторых пакетов (в данном случае msilib, cairo, numpy), в то время как для других конфигурации достаточно (в данном случае colorama) , Кроме того, теперь что-то из mingw64 тени usr (см. import magic).


    TLD; др
    [~]$ env | grep -i python
    PYTHONSTARTUP=/home/user1/.pythonrc
    PYTHONPATH=/c/Users/user1/Documents/appls_mydocs/PortableApps/MSYS2Portable/App/msys32/mingw64/lib/python3.7:/c/Users/user1/Documents/appls_mydocs/PortableApps/MSYS2Portable/App/msys32/mingw64/lib/python3.7/site-packages
    [~]$ python3
    Python 3.7.2 (default, Dec 26 2018, 08:23:20)
    [GCC 7.4.0] on msys
    Type "help", "copyright", "credits" or "license" for more information.
    Reading /home/user1/.pythonrc
    readline is in /usr/lib/python3.7/lib-dynload/readline.cpython-37m.dll
    >>> import sys
    >>> sys.path
    ['', '/c/Users/ry16205/Documents/appls_mydocs/PortableApps/MSYS2Portable/App/msys32/mingw64/lib/python3.7', '/c/Users/ry16205/Documents/appls_mydocs/PortableApps/MSYS2Portable/App/msys32/mingw64/lib/python3.7/site-packages', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/usr/lib/python3.7/site-packages']
    >>> import datetime
    >>> import json
    >>> import msilib
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/c/Users/ry16205/Documents/appls_mydocs/PortableApps/MSYS2Portable/App/msys32/mingw64/lib/python3.7/msilib/__init__.py", line 3, in <module>
        from _msi import *
    ModuleNotFoundError: No module named '_msi'
    >>> import cairo
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/c/Users/ry16205/Documents/appls_mydocs/PortableApps/MSYS2Portable/App/msys32/mingw64/lib/python3.7/site-packages/cairo/__init__.py", line 1, in <module>
        from ._cairo import *  # noqa: F401,F403
    ModuleNotFoundError: No module named 'cairo._cairo'
    >>> import colorama
    >>> import numpy                        <----------------------- This sparked the question
    Traceback (most recent call last):
      File "/c/Users/ry16205/Documents/appls_mydocs/PortableApps/MSYS2Portable/App/msys32/mingw64/lib/python3.7/site-packages/numpy/core/__init__.py", line 40, in <module>
        from . import multiarray
      File "/c/Users/ry16205/Documents/appls_mydocs/PortableApps/MSYS2Portable/App/msys32/mingw64/lib/python3.7/site-packages/numpy/core/multiarray.py", line 12, in <module>
        from . import overrides
      File "/c/Users/ry16205/Documents/appls_mydocs/PortableApps/MSYS2Portable/App/msys32/mingw64/lib/python3.7/site-packages/numpy/core/overrides.py", line 6, in <module>
        from numpy.core._multiarray_umath import (
    ModuleNotFoundError: No module named 'numpy.core._multiarray_umath'
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/c/Users/ry16205/Documents/appls_mydocs/PortableApps/MSYS2Portable/App/msys32/mingw64/lib/python3.7/site-packages/numpy/__init__.py", line 142, in <module>
        from . import core
      File "/c/Users/ry16205/Documents/appls_mydocs/PortableApps/MSYS2Portable/App/msys32/mingw64/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/python3),
         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.
    
    Original error was: No module named 'numpy.core._multiarray_umath'
    >>> import pip
    >>> import pytest
    >>> import magic
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/usr/lib/python3.7/site-packages/magic.py", line 61, in <module>
        _open = _libraries['magic'].magic_open
      File "/c/Users/ry16205/Documents/appls_mydocs/PortableApps/MSYS2Portable/App/msys32/mingw64/lib/python3.7/ctypes/__init__.py", line 369, in __getattr__
        func = self.__getitem__(name)
      File "/c/Users/ry16205/Documents/appls_mydocs/PortableApps/MSYS2Portable/App/msys32/mingw64/lib/python3.7/ctypes/__init__.py", line 374, in __getitem__                 
        func = self._FuncPtr((name_or_ordinal, self))                                                                                                                         
    AttributeError: function 'magic_open' not found                                                                                                                           
    

Мой .pythonrc:

import os
print( "Reading " + os.path.realpath(__file__) )

# enable syntax completion
try:
    import readline
    print( "readline is in " + readline.__file__ )
except ImportError:
    print("Module readline not available.")
else:
    import rlcompleter
    readline.parse_and_bind("tab: complete")

# From https://docs.python.org/2/tutorial/interactive.html

# Add auto-completion and a stored history file of commands to your Python
# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
# bound to the Esc key by default (you can change it - see readline docs).
#
# Store the file in ~/.pystartup, and set an environment variable to point
# to it:  "export PYTHONSTARTUP=~/.pystartup" in bash.

import atexit
import os
#import readline
#import rlcompleter

historyPath = os.path.expanduser("~/.pyhistory")

def save_history(historyPath=historyPath):
    import readline
    readline.write_history_file(historyPath)

if os.path.exists(historyPath):
    #import readline
    readline.read_history_file(historyPath)

atexit.register(save_history)
del os, atexit, readline, rlcompleter, save_history, historyPath
...