Import system python ошибка

I have an issue that has been discussed in some GitHub blogs but the answers there are so confusing and complex that I thought to ask here as well. Before asking, let me just say I'm not an expert

I have an issue that has been discussed in some GitHub blogs but the answers there are so confusing and complex that I thought to ask here as well.
Before asking, let me just say I’m not an expert programmer, so my apologizes if mine is a simple question.

  • I recently had to install Python 3.7

  • I used to have modules like clr and System working totally fine and now everything seems broker.
    I use Anaconda/Spyder to simply load the packages clr and System and Python gives me the following error messages:

    No module named ‘clr’
    No module named ‘System’

I managed to fix (apparently) the clr issue by running

pip install clr

from Anaconda Prompt.
However, in order to fix the issue with the System module, it seems I need to install pythonnet (I don’t knoww exactly what it is but I guess it doesn’t matter).
Based on anaconda official website: https://anaconda.org/pythonnet/pythonnet I should simply run:

conda install -c pythonnet pythonnet

But that doesn’t work.
My extremely limited understanding is that something is going wrong between Pythonnet and Python 3.7.
Does anybody have a clue of what I should do?

Dharman's user avatar

Dharman

29.3k21 gold badges80 silver badges131 bronze badges

asked Jun 15, 2020 at 18:42

Angelo's user avatar

2

you should use this:

import clr

clr.AddReference('System')

from System import String

betelgeuse's user avatar

betelgeuse

1,0543 gold badges11 silver badges25 bronze badges

answered Dec 15, 2021 at 6:17

swordxwind's user avatar

1

What eventually worked for me, after messing around with my packages, was to: 1. uninstall clr. 2. Uninstall pythonnet. 3. Only at this point, I had to reinstall pythonnet. This sequence fixed my problem.

pip uninstall clr
pip uninstall pythonnet 
pip install pythonnet 

answered Jan 31, 2022 at 22:03

Angelo's user avatar

AngeloAngelo

1,3913 gold badges16 silver badges40 bronze badges

In my Python3, System is not a module — it’s a method of the os module.

so I use

from os import system

then

system("<<Put Your Command Here>>")

If you want it called System with a capital S (maybe for backward compatability with already-written programs?), use

from os import system as System

answered Jul 14, 2020 at 19:54

ExperiMentor's user avatar

3

I have an issue that has been discussed in some GitHub blogs but the answers there are so confusing and complex that I thought to ask here as well.
Before asking, let me just say I’m not an expert programmer, so my apologizes if mine is a simple question.

  • I recently had to install Python 3.7

  • I used to have modules like clr and System working totally fine and now everything seems broker.
    I use Anaconda/Spyder to simply load the packages clr and System and Python gives me the following error messages:

    No module named ‘clr’
    No module named ‘System’

I managed to fix (apparently) the clr issue by running

pip install clr

from Anaconda Prompt.
However, in order to fix the issue with the System module, it seems I need to install pythonnet (I don’t knoww exactly what it is but I guess it doesn’t matter).
Based on anaconda official website: https://anaconda.org/pythonnet/pythonnet I should simply run:

conda install -c pythonnet pythonnet

But that doesn’t work.
My extremely limited understanding is that something is going wrong between Pythonnet and Python 3.7.
Does anybody have a clue of what I should do?

Dharman's user avatar

Dharman

29.3k21 gold badges80 silver badges131 bronze badges

asked Jun 15, 2020 at 18:42

Angelo's user avatar

2

you should use this:

import clr

clr.AddReference('System')

from System import String

betelgeuse's user avatar

betelgeuse

1,0543 gold badges11 silver badges25 bronze badges

answered Dec 15, 2021 at 6:17

swordxwind's user avatar

1

What eventually worked for me, after messing around with my packages, was to: 1. uninstall clr. 2. Uninstall pythonnet. 3. Only at this point, I had to reinstall pythonnet. This sequence fixed my problem.

pip uninstall clr
pip uninstall pythonnet 
pip install pythonnet 

answered Jan 31, 2022 at 22:03

Angelo's user avatar

AngeloAngelo

1,3913 gold badges16 silver badges40 bronze badges

In my Python3, System is not a module — it’s a method of the os module.

so I use

from os import system

then

system("<<Put Your Command Here>>")

If you want it called System with a capital S (maybe for backward compatability with already-written programs?), use

from os import system as System

answered Jul 14, 2020 at 19:54

ExperiMentor's user avatar

3

@satanasss

Hi guys,

I’m trying to use to do an import System in my python code but it won’t work.

Here is what I do:
Import clr
Import System

inportError: No module named System

So I tried a clr.AddReference, same thing, «AttributeError: ‘module’ object has no attribute ‘AddReference’

Have you guys already had this pb ? Do you need more info ?

Thanks in advance

Environment

  • Pythonnet version: 2.2.2
  • Clr version 1.0.2
  • Python version: 2.7.1 anaconda 2.4.1
  • Operating System: windows

Details

  • Describe what you were trying to get done.

    TODO

  • What commands did you run to trigger this issue? If you can provide a
    Minimal, Complete, and Verifiable example
    this will help us understand the issue.

  • If there was a crash, please include the traceback here.

@denfromufa

Where did you get this `Clr version 1.0.2`?
Is it this package?

https://pypi.python.org/pypi/clr/1.0.3

If yes, you need to uninstall this clr package to use pythonnet, because
both packages have a name clash.

On Thu, Feb 16, 2017, 8:27 PM satanasss ***@***.***> wrote:
Hi guys,

I’m trying to use to do an import System in my python code but it won’t
work.

Here is what I do:
Import clr
Import System

inportError: No module named System

So I tried a clr.AddReference, same thing, «AttributeError: ‘module’
object has no attribute ‘AddReference’

Have you guys already had this pb ? Do you need more info ?

Thanks in advance
Environment

— Pythonnet version: 2.2.2
— Clr version 1.0.2
— Python version: 2.7.1 anaconda 2.4.1
— Operating System: windows

Details

Describe what you were trying to get done.

*TODO*

What commands did you run to trigger this issue? If you can provide a
Minimal, Complete, and Verifiable example
<http://stackoverflow.com/help/mcve>
this will help us understand the issue.

print(‘TODO’)

— If there was a crash, please include the traceback here.

print(‘TODO’)


You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
<#388>, or mute the thread
<https://github.com/notifications/unsubscribe-auth/AHgZ5aYSfKUmewxvv-Jj6iizDFPiRW1Sks5rdQWjgaJpZM4MDzI9>
.

@denfromufa

You can also try using importlib to import clr from pythonnet with full
path provided to clr.pyd.

On Thu, Feb 16, 2017, 8:35 PM Denis Akhiyarov <denis.akhiyarov@gmail.com>
wrote:

Where did you get this `Clr version 1.0.2`?
Is it this package?

https://pypi.python.org/pypi/clr/1.0.3

If yes, you need to uninstall this clr package to use pythonnet, because
both packages have a name clash.

On Thu, Feb 16, 2017, 8:27 PM satanasss ***@***.***> wrote:

Hi guys,

I’m trying to use to do an import System in my python code but it won’t
work.

Here is what I do:
Import clr
Import System

inportError: No module named System

So I tried a clr.AddReference, same thing, «AttributeError: ‘module’
object has no attribute ‘AddReference’

Have you guys already had this pb ? Do you need more info ?

Thanks in advance
Environment

— Pythonnet version: 2.2.2
— Clr version 1.0.2
— Python version: 2.7.1 anaconda 2.4.1
— Operating System: windows

Details

Describe what you were trying to get done.

*TODO*

What commands did you run to trigger this issue? If you can provide a
Minimal, Complete, and Verifiable example
<http://stackoverflow.com/help/mcve>
this will help us understand the issue.

print(‘TODO’)

— If there was a crash, please include the traceback here.

print(‘TODO’)


You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
<#388>, or mute the thread
<https://github.com/notifications/unsubscribe-auth/AHgZ5aYSfKUmewxvv-Jj6iizDFPiRW1Sks5rdQWjgaJpZM4MDzI9>
.

@satanasss

Wow thanks for the quick answer ! Indeed getting rid of clr and reinstalling pyhtonnet fixed the stuff.

Many thanks guys !

@vmuriart

In retrospective we should have registered that package name in PyPi

@denfromufa

I think there is a way to «complain» to pypi members, so that this clashing is resolved.

This clr package is only about one month old.

But let’s wait over the weekends, if the author responds.

@filmor

I’ve pinged him again to get to a decision: lmittmann/style#1

In case he does not want to give up the name we should:

  • Add information to our README.md that one must make sure that pythonnet installed via pip
  • Add the same information to our pypi channel and homepage

In case he does:

  • We have to grab the clr name on pypi and essentially alias it to pythonnet, for example by putting a package there that prints a warning and depends on pythonnet

@filmor

@denfromufa @vmuriart I have added you as owners of the clr package on PyPI. I don’t have the time to finish the work there right now, so here’s the TODO list :)

  • Put up a new package information page that is basically our usual README but adds a disclaimer that the previously listed package is now called style and that the «real» name of the Python.NET package is pythonnet
  • Create a small package (i.e. setup.py) within our git-repo that only depends on pythonnet
  • Remove the existing clr package and push our alias-package

@denfromufa

We may as well reserve Python.net package name on pypi.

@eabase

I just got this error and found out it was due to having multiple Python installations, including pythonnet package install in each.

  1. If, you’re in Windows, do: where.exe python to find where it’s installed.
  2. Next, use the version specific pip, like this:

(depending on what you found in (1).)

The version I am using, is conda so scripts installed with conda and using import clr, fails with:
ModuleNotFoundError: No module named 'clr'
when ran from command line.

I don’t know how to fix this.

However, running script in it’s own home directory (elsewhere) seem to work. Very weird!

Порой бывает трудно правильно реализовать import с первого раза, особенно если мы хотим добиться правильной работы на плохо совместимых между собой версиях Python 2 и Python 3. Попытаемся разобраться, что из себя представляют импорты в Python и как написать решение, которое подойдёт под обе версии языка.

Содержание

  • Ключевые моменты
  • Основные определения
  • Пример структуры директорий
  • Что делает import
  • Основы import и sys.path
  • Чуть подробнее о sys.path
  • Всё о __init__.py
  • Использование объектов из импортированного модуля или пакета
  • Используем dir() для исследования содержимого импортированного модуля
  • Импортирование пакетов
  • Абсолютный и относительный импорт
  • Примеры
  • Python 2 vs Python 3
  • Прочие темы, не рассмотренные здесь, но достойные упоминания

Ключевые моменты

  • Выражения import производят поиск по списку путей в sys.path.
  • sys.path всегда включает в себя путь скрипта, запущенного из командной строки, и не зависит от текущей рабочей директории.
  • Импортирование пакета по сути равноценно импортированию  __init__.py этого пакета.

Основные определения

  • Модуль: любой файл *.py. Имя модуля — имя этого файла.
  • Встроенный модуль: «модуль», который был написан на Си, скомпилирован и встроен в интерпретатор Python, и потому не имеет файла *.py.
  • Пакет: любая папка, которая содержит файл __init__.py. Имя пакета — имя папки.
    • С версии Python 3.3 любая папка (даже без __init__.py) считается пакетом.
  • Объект: в Python почти всё является объектом — функции, классы, переменные и т. д.

Пример структуры директорий

test/                      # Корневая папка
    packA/                 # Пакет packA
        subA/              # Подпакет subA
            __init__.py
            sa1.py
            sa2.py
        __init__.py
        a1.py
        a2.py
    packB/                 # Пакет packB (неявный пакет пространства имён)
        b1.py
        b2.py
    math.py
    random.py
    other.py
    start.py

Обратите внимание, что в корневой папке test/ нет файла __init__.py.

Что делает import

При импорте модуля Python выполняет весь код в нём. При импорте пакета Python выполняет код в файле пакета __init__.py, если такой имеется. Все объекты, определённые в модуле или __init__.py, становятся доступны импортирующему.

Основы import и sys.path

Вот как оператор import производит поиск нужного модуля или пакета согласно документации Python:

При импорте модуля spam интерпретатор сначала ищёт встроенный модуль с таким именем. Если такого модуля нет, то идёт поиск файла spam.py в списке директорий, определённых в переменной sys.path. sys.path инициализируется из следующих мест:

  • директории, содержащей исходный скрипт (или текущей директории, если файл не указан);
  • директории по умолчанию, которая зависит от дистрибутива Python;
  • PYTHONPATH (список имён директорий; имеет синтаксис, аналогичный переменной окружения PATH).

Программы могут изменять переменную sys.path после её инициализации. Директория, содержащая запускаемый скрипт, помещается в начало поиска перед путём к стандартной библиотеке. Это значит, что скрипты в этой директории будут импортированы вместо модулей с такими же именами в стандартной библиотеке.

Источник: Python 2 и Python 3

Технически документация не совсем полна. Интерпретатор будет искать не только файл (модуль) spam.py, но и папку (пакет) spam.

Обратите внимание, что Python сначала производит поиск среди встроенных модулей — тех, которые встроены непосредственно в интерпретатор. Список встроенных модулей зависит от дистрибутива Python, а найти этот список можно в sys.builtin_module_names (Python 2 и Python 3). Обычно в дистрибутивах есть модули sys (всегда включён в дистрибутив), math, itertools, time и прочие.

В отличие от встроенных модулей, которые при поиске проверяются первыми, остальные (не встроенные) модули стандартной библиотеки проверяются после директории запущенного скрипта. Это приводит к сбивающему с толку поведению: возможно «заменить» некоторые, но не все модули стандартной библиотеки. Допустим, модуль math является встроенным модулем, а random — нет. Таким образом, import math в start.py импортирует модуль из стандартной библиотеки, а не наш файл math.py из той же директории. В то же время, import random в start.py импортирует наш файл random.py.

Кроме того, импорты в Python регистрозависимы: import Spam и import spam — разные вещи.

Функцию pkgutil.iter_modules() (Python 2 и Python 3) можно использовать, чтобы получить список всех модулей, которые можно импортировать из заданного пути:

import pkgutil
search_path = ['.'] # Используйте None, чтобы увидеть все модули, импортируемые из sys.path
all_modules = [x[1] for x in pkgutil.iter_modules(path=search_path)]
print(all_modules)

Чуть подробнее о sys.path

Чтобы увидеть содержимое sys.path, запустите этот код:

import sys
print(sys.path)

Документация Python описывает sys.path так:

Список строк, указывающих пути для поиска модулей. Инициализируется из переменной окружения PYTHONPATH и директории по умолчанию, которая зависит от дистрибутива Python.

При запуске программы после инициализации первым элементом этого списка, path[0], будет директория, содержащая скрипт, который был использован для вызова интерпретатора Python. Если директория скрипта недоступна (например, если интерпретатор был вызван в интерактивном режиме или скрипт считывается из стандартного ввода), то path[0] является пустой строкой. Из-за этого Python сначала ищет модули в текущей директории. Обратите внимание, что директория скрипта вставляется перед путями, взятыми из PYTHONPATH.

Источник: Python 2 и Python 3

Документация к интерфейсу командной строки Python добавляет информацию о запуске скриптов из командной строки. В частности, при запуске python <script>.py.

Если имя скрипта ссылается непосредственно на Python-файл, то директория, содержащая этот файл, добавляется в начало sys.path, а файл выполняется как модуль main.

Источник: Python 2 и Python 3

Итак, повторим порядок, согласно которому Python ищет импортируемые модули:

  1. Модули стандартной библиотеки (например, math, os).
  2. Модули или пакеты, указанные в sys.path:
      1. Если интерпретатор Python запущен в интерактивном режиме:
        • sys.path[0] — пустая строка ''. Это значит, что Python будет искать в текущей рабочей директории, из которой вы запустили интерпретатор. В Unix-системах эту директорию можно узнать с помощью команды pwd.

        Если мы запускаем скрипт командой python <script>.py:

        • sys.path[0] — это путь к <script>.py.
      2. Директории, указанные в переменной среды PYTHONPATH.
      3. Директория по умолчанию, которая зависит от дистрибутива Python.

Обратите внимание, что при запуске скрипта для sys.path важна не директория, в которой вы находитесь, а путь к самому скрипту. Например, если в командной строке мы находимся в test/folder и запускаем команду python ./packA/subA/subA1.py, то sys.path будет включать в себя test/packA/subA/, но не test/.

Кроме того, sys.path общий для всех импортируемых модулей. Допустим, мы вызвали python start.py. Пусть start.py импортирует packA.a1, а a1.py выводит на экран sys.path. В таком случае sys.path будет включать test/ (путь к start.py), но не test/packA (путь к a1.py). Это значит, что a1.py может вызвать import other, так как other.py находится в test/.

Всё о __init__.py

У файла __init__.py есть две функции:

  1. Превратить папку со скриптами в импортируемый пакет модулей (до Python 3.3).
  2. Выполнить код инициализации пакета.

Превращение папки со скриптами в импортируемый пакет модулей

Чтобы импортировать модуль (или пакет) из директории, которая находится не в директории нашего скрипта (или не в директории, из которой мы запускаем интерактивный интерпретатор), этот модуль должен быть в пакете.

Как было сказано ранее, любая директория, содержащая файл __init__.py, является пакетом. Например, при работе с Python 2.7 start.py может импортировать пакет packA, но не packB, так как в директории test/packB/ нет файла __init__.py.

Это не относится к Python 3.3 и выше благодаря появлению неявных пакетов пространств имён. Проще говоря, в Python 3.3+ все папки считаются пакетами, поэтому пустые файлы __init__.py больше не нужны.

Допустим, packB — пакет пространства имён, так как в нём нет __init__.py. Если запустить интерактивную оболочку Python 3.6 в директории test/, то мы увидим следующее:

>>> import packB
>>> packB
<module 'packB' (namespace)>

Выполнение кода инициализации пакета

В момент, когда пакет или один из его модулей импортируется в первый раз, Python выполняет __init__.py в корне пакета, если такой файл существует. Все объекты и функции, определённые в __init__.py, считаются частью пространства имён пакета.

Рассмотрим следующий пример:

test/packA/a1.py

def a1_func():
    print("Выполняем a1_func()")

test/packA/__init__.py

## Этот импорт делает функцию a1_func() доступной напрямую из packA.a1_func
from packA.a1 import a1_func

def packA_func():
    print("Выполняем packA_func()")

test/start.py

import packA  # «import packA.a1» сработает точно так же

packA.packA_func()
packA.a1_func()
packA.a1.a1_func()

Вывод после запуска python start.py:

Выполняем packA_func()
Выполняем a1_func()
Выполняем a1_func()

Примечание Если a1.py вызовет import a2, и мы запустим python a1.py, то test/packA/__init__.py не будет вызван, несмотря на то, что a2 вроде бы является частью пакета packA. Это связано с тем, что когда Python выполняет скрипт (в данном случае a1.py), содержащая его папка не считается пакетом.

Использование объектов из импортированного модуля или пакета

Есть 4 разных вида импортов:

  1. import <пакет>
  2. import <модуль>
  3. from <пакет> import <модуль или подпакет или объект>
  4. from <модуль> import <объект>

Пусть X — имя того, что идёт после import:

  • Если X — имя модуля или пакета, то для того, чтобы использовать объекты, определённые в X, придётся писать X.объект.
  • Если X — имя переменной, то её можно использовать напрямую.
  • Если X — имя функции, то её можно вызвать с помощью X().

Опционально после любого выражения import X можно добавить as Y. Это переименует X в Y в пределах скрипта. Учтите, что имя X с этого момента становится недействительным. Частым примером такой конструкции является import numpy as np.

Аргументом для import может быть как одно имя, так и их список. Каждое из имён можно переименовать с помощью as. Например, следующее выражение будет действительно в start.py: import packA as pA, packA.a1, packA.subA.sa1 as sa1.

Пример: нужно в start.py импортировать функцию helloWorld() из sa1.py.

  • Решение 1: from packA.subA.sa1 import helloWorld. Мы можем вызвать функцию напрямую по имени: x = helloWorld().
  • Решение 2: from packA.subA import sa1 или то же самое import packA.subA.sa1 as sa1. Для использования функции нам нужно добавить перед её именем имя модуля: x = sa1.helloWorld(). Иногда такой подход предпочтительнее первого, так как становится ясно, из какого модуля взялась та или иная функция.
  • Решение 3: import packA.subA.sa1. Для использования функции перед её именем нужно добавить полный путь: x = packA.subA.sa1.helloWorld().

Прим. перев. После переименования с помощью as новое имя нельзя использовать в качестве имени пакета или модуля для последующих импортов. Иными словами, команда вроде следующей недействительна: import packA as pA, pA.a1.

Используем dir() для исследования содержимого импортированного модуля

После импортирования модуля можно использовать функцию dir() для получения списка доступных в модуле имён. Допустим, мы импортируем sa1. Если в sa1.py есть функция helloWorld(), то dir(sa1) будет включать helloWorld:

>>> from packA.subA import sa1
>>> dir(sa1)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'helloWorld']

Импортирование пакетов

Импортирование пакета по сути равноценно импортированию его __init__.py. Вот как Python на самом деле видит пакет:

>>> import packA
>>> packA
<module 'packA' from 'packA/__init__.py'>

После импорта становятся доступны только те объекты, что определены в __init__.py пакета. Поскольку в packB нет такого файла, от import packB (в Python 3.3.+) будет мало толку, так как никакие объекты из этого пакета не становятся доступны. Последующий вызов модуля packB.b1 приведёт к ошибке, так как он ещё не был импортирован.

Абсолютный и относительный импорт

При абсолютном импорте используется полный путь (от начала корневой папки проекта) к желаемому модулю.

При относительном импорте используется относительный путь (начиная с пути текущего модуля) к желаемому модулю. Есть два типа относительных импортов:

  1. При явном импорте используется формат from .<модуль/пакет> import X, где символы точки . показывают, на сколько директорий «вверх» нужно подняться. Одна точка . показывает текущую директорию, две точки .. — на одну директорию выше и т. д.
  2. Неявный относительный импорт пишется так, как если бы текущая директория была частью sys.path. Такой тип импортов поддерживается только в Python 2.

В документации Python об относительных импортах в Python 3 написано следующее:

Единственный приемлемый синтаксис для относительных импортов — from .[модуль] import [имя]. Все импорты, которые начинаются не с точки ., считаются абсолютными.

Источник: What’s New in Python 3.0

В качестве примера допустим, что мы запускаем start.py, который импортирует a1, который импортирует other, a2 и sa1. Тогда импорты в a1.py будут выглядеть следующим образом:

Абсолютные импорты:

import other
import packA.a2
import packA.subA.sa1

Явные относительные импорты:

import other
from . import a2
from .subA import sa1

Неявные относительные импорты (не поддерживаются в Python 3):

import other
import a2
import subA.sa1

Учтите, что в относительных импортах с помощью точек . можно дойти только до директории, содержащей запущенный из командной строки скрипт (не включительно). Таким образом, from .. import other не сработает в a1.py. В результате мы получим ошибку ValueError: attempted relative import beyond top-level package.

Как правило, абсолютные импорты предпочтительнее относительных. Они позволяют избежать путаницы между явными и неявными импортами. Кроме того, любой скрипт с явными относительными импортами нельзя запустить напрямую:

Имейте в виду, что относительные импорты основаны на имени текущего модуля. Так как имя главного модуля всегда "__main__", модули, которые должны использоваться как главный модуль приложения, должны всегда использовать абсолютные импорты.

Источник: Python 2 и Python 3

Примеры

Пример 1: sys.path известен заранее

Если вы собираетесь вызывать только python start.py или python other.py, то прописать импорты всем модулям не составит труда. В данном случае sys.path всегда будет включать папку test/. Таким образом, все импорты можно писать относительно этой папки.

Пример: файлу в проекте test нужно импортировать функцию helloWorld() из sa1.py.

Решение: from packA.subA.sa1 import helloWorld (или любой другой эквивалентный синтаксис импорта).

Пример 2: sys.path мог измениться

Зачастую нам требуется как запускать скрипт напрямую из командной строки, так и импортировать его как модуль в другом скрипте. Как вы увидите далее, здесь могут возникнуть проблемы, особенно в Python 3.

Пример: пусть start.py нужно импортировать a2, которому нужно импортировать sa2. Предположим, что start.py всегда запускается напрямую, а не импортируется. Также мы хотим иметь возможность запускать a2 напрямую.

Звучит просто, не так ли? Нам всего лишь нужно выполнить два импорта: один в start.py и другой в a2.py.

Проблема: это один из тех случаев, когда sys.path меняется. Когда мы выполняем start.py, sys.path содержит test/, а при выполнении a2.py sys.path содержит test/packA/.

С импортом в start.py нет никаких проблем. Так как этот модуль всегда запускается напрямую, мы знаем, что при его выполнении в sys.path всегда будет test/. Тогда импортировать a2 можно просто с помощью import packA.a2.

С импортом в a2.py немного сложнее. Когда мы запускаем start.py напрямую, sys.path содержит test/, поэтому в a2.py импорт будет выглядеть как from packA.subA import sa2. Однако если запустить a2.py напрямую, то в sys.path уже будет test/packA/. Теперь импорт вызовет ошибку, так как packA не является папкой внутри test/packA/.

Вместо этого мы могли бы попробовать from subA import sa2. Это решает проблему при запуске a2.py напрямую, однако теперь создаёт проблему при запуске start.py. В Python 3 это приведёт к ошибке, потому что subA не находится в sys.path (в Python 2 это не вызовет проблемы из-за поддержки неявных относительных импортов).

Обобщим информацию:

Запускаем from packA.subA import sa2 from subA import sa2
start.py Нет проблем В Py2 нет проблем, в Py3 ошибка (subA не в test/)
a2.py Ошибка (packA не в test/packA/) Нет проблем

Использование относительного импорта from .subA import sa2 будет иметь тот же эффект, что и from packA.subA import sa2.

Вряд ли для этой проблемы есть чистое решение, поэтому вот несколько обходных путей:

1. Использовать абсолютные импорты относительно директории test/ (т. е. средняя колонка в таблице выше). Это гарантирует, что запуск start.py напрямую всегда сработает. Чтобы запустить a2.py напрямую, запустите его как импортируемый модуль, а не как скрипт:

  1. В консоли смените директорию на  test/.
  2. Запустите python -m packA.a2.

2. Использовать абсолютные импорты относительно директории test/ (средняя колонка в таблице). Это гарантирует, что запуск start.py напрямую всегда сработает. Чтобы запустить a2.py напрямую, можно изменить sys.path в a2.py, чтобы включить test/packA/ перед импортом sa2.

import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))

# Теперь это сработает даже если a2.py будет запущен напрямую
from packA.subA import sa2

Примечание Обычно этот метод работает, однако в некоторых случаях переменная __file__ может быть неправильной. В таком случае нужно использовать встроенный пакет inspect. Подробнее в этом ответе на StackOverflow.

3. Использовать только Python 2 и неявные относительные импорты (последняя колонка в таблице).

4. Использовать абсолютные импорты относительно директории test/ и добавить её в переменную среды PYTHONPATH. Это решение не переносимо, поэтому лучше не использовать его. О том, как добавить директорию в PYTHONPATH, читайте в этом ответе.

Пример 3: sys.path мог измениться (вариант 2)

А вот ещё одна проблема посложнее. Допустим, модуль a2.py никогда не надо запускать напрямую, но он импортируется start.py и a1.py, которые запускаются напрямую.

В этом случае первое решение из примера выше не сработает. Тем не менее, всё ещё можно использовать остальные решения.

Пример 4: импорт из родительской директории

Если мы не изменяем PYTHONPATH и стараемся не изменять sys.path программно, то сталкиваемся со следующим основным ограничением импортов в Python: при запуске скрипта напрямую невозможно импортировать что-либо из его родительской директории.

Например, если бы нам пришлось запустить python sa1.py, то этот модуль не смог бы ничего импортировать из a1.py без вмешательства в PYTHONPATH или sys.path.

На первый взгляд может показаться, что относительные импорты (например from .. import a1) помогут решить эту проблему. Однако запускаемый скрипт (в данном случае sa1.py) считается «модулем верхнего уровня». Попытка импортировать что-либо из директории над этим скриптом приведёт к ошибке ValueError: attempted relative import beyond top-level package.

Для решения этой проблемы лучше её не создавать и избегать написания скриптов, которые импортируют из родительской директории. Если этого нельзя избежать, то предпочтительным обходным путём является изменение sys.path.

Python 2 vs Python 3

Мы разобрали основные отличия импортов в Python 2 и Python 3. Они ещё раз изложены здесь наряду с менее важными отличиями:

  1. Python 2 поддерживает неявные относительные импорты, Python 3 — нет.
  2. В Python 2, чтобы папка считалась пакетом и её можно было импортировать, она должна содержать файл __init__.py. С версии Python 3.3 благодаря введению неявных пакетов пространств имён все папки считаются пакетами вне зависимости от наличия __init__.py.
  3. В Python 2 можно написать from <модуль> import * внутри функции, а в Python 3 — только на уровне модуля.

Ещё немного полезной информации по импортам

  • Можно использовать переменную __all__ в __init__.py, чтобы указать, что будет импортировано выражением from <модуль> import *. Смотрите документацию для Python 2 и Python 3.
  • Можно использовать if __name__ == '__main__' для проверки, был ли скрипт импортирован или запущен напрямую. Документация для Python 2 и Python 3.
  • Можно установить проект в качестве пакета (в режиме разработчика) с помощью pip install -e <проект>, чтобы добавить корень проекта в sys.path. Подробнее в этом ответе на StackOverflow.
  • from <модуль> import * не импортирует имена из модуля, которые начинаются с нижнего подчеркивания _. Подробнее читайте в документации Python 2 и Python 3.

Перевод статьи «The Definitive Guide to Python import Statements»

Python is installed in a local directory.

My directory tree looks like this:

(local directory)/site-packages/toolkit/interface.py

My code is in here:

(local directory)/site-packages/toolkit/examples/mountain.py

To run the example, I write python mountain.py, and in the code I have:

from toolkit.interface import interface

And I get the error:

Traceback (most recent call last):
  File "mountain.py", line 28, in ?
    from toolkit.interface import interface
ImportError: No module named toolkit.interface

I have already checked sys.path and there I have the directory /site-packages. Also, I have the file __init__.py.bin in the toolkit folder to indicate to Python that this is a package. I also have a __init__.py.bin in the examples directory.

I do not know why Python cannot find the file when it is in sys.path. Any ideas? Can it be a permissions problem? Do I need some execution permission?

alex's user avatar

alex

6,3319 gold badges50 silver badges102 bronze badges

asked Dec 3, 2008 at 21:26

Eduardo's user avatar

7

Based on your comments to orip’s post, I guess this is what happened:

  1. You edited __init__.py on windows.
  2. The windows editor added something non-printing, perhaps a carriage-return (end-of-line in Windows is CR/LF; in unix it is LF only), or perhaps a CTRL-Z (windows end-of-file).
  3. You used WinSCP to copy the file to your unix box.
  4. WinSCP thought: «This has something that’s not basic text; I’ll put a .bin extension to indicate binary data.»
  5. The missing __init__.py (now called __init__.py.bin) means python doesn’t understand toolkit as a package.
  6. You create __init__.py in the appropriate directory and everything works… ?

answered Dec 4, 2008 at 0:17

John Fouhy's user avatar

John FouhyJohn Fouhy

40.5k19 gold badges62 silver badges77 bronze badges

8

Does

(local directory)/site-packages/toolkit

have a __init__.py?

To make import walk through your directories every directory must have a __init__.py file.

answered Dec 3, 2008 at 21:50

igorgue's user avatar

igorgueigorgue

17.6k13 gold badges37 silver badges52 bronze badges

2

I ran into something very similar when I did this exercise in LPTHW; I could never get Python to recognise that I had files in the directory I was calling from. But I was able to get it to work in the end. What I did, and what I recommend, is to try this:

(NOTE: From your initial post, I am assuming you are using an *NIX-based machine and are running things from the command line, so this advice is tailored to that. Since I run Ubuntu, this is what I did)

  1. Change directory (cd) to the directory above the directory where your files are. In this case, you’re trying to run the mountain.py file, and trying to call the toolkit.interface.py module, which are in separate directories. In this case, you would go to the directory that contains paths to both those files (or in other words, the closest directory that the paths of both those files share). Which in this case is the toolkit directory.

  2. When you are in the toolkit directory, enter this line of code on your command line:

    export PYTHONPATH=.

    This sets your PYTHONPATH to «.», which basically means that your PYTHONPATH will now look for any called files within the directory you are currently in, (and more to the point, in the sub-directory branches of the directory you are in. So it doesn’t just look in your current directory, but in all the directories that are in your current directory).

  3. After you’ve set your PYTHONPATH in the step above, run your module from your current directory (the toolkit directory). Python should now find and load the modules you specified.

user's user avatar

user

4,8906 gold badges17 silver badges35 bronze badges

answered Apr 22, 2014 at 3:52

Specterace's user avatar

SpecteraceSpecterace

1,0057 silver badges7 bronze badges

4

On *nix, also make sure that PYTHONPATH is configured correctly, especially that it has this format:

 .:/usr/local/lib/python

(Mind the .: at the beginning, so that it can search on the current directory, too.)

It may also be in other locations, depending on the version:

 .:/usr/lib/python
 .:/usr/lib/python2.6
 .:/usr/lib/python2.7 and etc.

Peter Mortensen's user avatar

answered Mar 4, 2011 at 21:14

Renaud's user avatar

RenaudRenaud

15.7k6 gold badges79 silver badges78 bronze badges

6

You are reading this answer says that your __init__.py is in the right place, you have installed all the dependencies and you are still getting the ImportError.

I was facing a similar issue except that my program would run fine when ran using PyCharm but the above error when I would run it from the terminal. After digging further, I found out that PYTHONPATH didn’t have the entry for the project directory. So, I set PYTHONPATH per Import statement works on PyCharm but not from terminal:

export PYTHONPATH=$PYTHONPATH:`pwd`  (OR your project root directory)

There’s another way to do this using sys.path as:

import sys
sys.path.insert(0,'<project directory>') OR
sys.path.append('<project directory>')

You can use insert/append based on the order in which you want your project to be searched.

jww's user avatar

jww

95k88 gold badges397 silver badges861 bronze badges

answered Feb 8, 2019 at 16:57

avp's user avatar

avpavp

2,76228 silver badges33 bronze badges

4

Using PyCharm (part of the JetBrains suite) you need to define your script directory as Source:
Right Click > Mark Directory as > Sources Root

answered Jan 4, 2017 at 17:53

MonoThreaded's user avatar

MonoThreadedMonoThreaded

11.2k11 gold badges69 silver badges100 bronze badges

2

For me, it was something really stupid. I installed the library using pip3 install but was running my program as python program.py as opposed to python3 program.py.

Nicolas Gervais's user avatar

answered Aug 22, 2019 at 16:02

kev's user avatar

kevkev

2,6513 gold badges21 silver badges45 bronze badges

1

I solved my own problem, and I will write a summary of the things that were wrong and the solution:

The file needs to be called exactly __init__.py. If the extension is different such as in my case .py.bin then Python cannot move through the directories and then it cannot find the modules. To edit the files you need to use a Linux editor, such as vi or nano. If you use a Windows editor this will write some hidden characters.

Another problem that was affecting it was that I had another Python version installed by the root, so if someone is working with a local installation of python, be sure that the Python installation that is running the programs is the local Python. To check this, just do which python, and see if the executable is the one that is in your local directory. If not, change the path, but be sure that the local Python directory is before than the other Python.

Peter Mortensen's user avatar

answered Dec 4, 2008 at 1:11

Eduardo's user avatar

EduardoEduardo

19.4k22 gold badges63 silver badges73 bronze badges

3

To mark a directory as a package you need a file named __init__.py, does this help?

answered Dec 3, 2008 at 21:31

orip's user avatar

oriporip

71.9k21 gold badges118 silver badges147 bronze badges

8

an easy solution is to install the module using python -m pip install <library-name> instead of pip install <library-name>
you may use sudo in case of admin restrictions

answered Sep 18, 2017 at 15:30

Badr Bellaj's user avatar

Badr BellajBadr Bellaj

10.6k2 gold badges40 silver badges40 bronze badges

3

To all those who still have this issue. I believe Pycharm gets confused with imports. For me, when i write ‘from namespace import something’, the previous line gets underlined in red, signaling that there is an error, but works. However »from .namespace import something’ doesn’t get underlined, but also doesn’t work.

Try

try:
    from namespace import something 
except NameError:
    from .namespace import something

answered May 11, 2019 at 19:34

AKJ's user avatar

AKJAKJ

8522 gold badges13 silver badges18 bronze badges

1

Yup. You need the directory to contain the __init__.py file, which is the file that initializes the package. Here, have a look at this.

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.

Raphael Schweikert's user avatar

answered Jan 7, 2009 at 14:22

miya's user avatar

miyamiya

1,0591 gold badge11 silver badges20 bronze badges

If you have tried all methods provided above but failed, maybe your module has the same name as a built-in module. Or, a module with the same name existing in a folder that has a high priority in sys.path than your module’s.

To debug, say your from foo.bar import baz complaints ImportError: No module named bar. Changing to import foo; print foo, which will show the path of foo. Is it what you expect?

If not, Either rename foo or use absolute imports.

answered May 2, 2017 at 6:41

liushuaikobe's user avatar

liushuaikobeliushuaikobe

2,1221 gold badge23 silver badges26 bronze badges

1

  1. You must have the file __ init__.py in the same directory where it’s the file that you are importing.
  2. You can not try to import a file that has the same name and be a file from 2 folders configured on the PYTHONPATH.

eg:
/etc/environment

PYTHONPATH=$PYTHONPATH:/opt/folder1:/opt/folder2

/opt/folder1/foo

/opt/folder2/foo

And, if you are trying to import foo file, python will not know which one you want.

from foo import … >>> importerror: no module named foo

answered Jan 9, 2014 at 19:45

Iasmini Gomes's user avatar

Iasmini GomesIasmini Gomes

6671 gold badge8 silver badges14 bronze badges

0

My two cents:

enter image description here

Spit:

Traceback (most recent call last):
      File "bashbash.py", line 454, in main
        import bosh
      File "Wrye Bash Launcher.pyw", line 63, in load_module
        mod = imp.load_source(fullname,filename+ext,fp)
      File "bashbosh.py", line 69, in <module>
        from game.oblivion.RecordGroups import MobWorlds, MobDials, MobICells, 
    ImportError: No module named RecordGroups

This confused the hell out of me — went through posts and posts suggesting ugly syspath hacks (as you see my __init__.py were all there). Well turns out that game/oblivion.py and game/oblivion was confusing python
which spit out the rather unhelpful «No module named RecordGroups». I’d be interested in a workaround and/or links documenting this (same name) behavior -> EDIT (2017.01.24) — have a look at What If I Have a Module and a Package With The Same Name? Interestingly normally packages take precedence but apparently our launcher violates this.

EDIT (2015.01.17): I did not mention we use a custom launcher dissected here.

Community's user avatar

answered Sep 6, 2014 at 11:17

Mr_and_Mrs_D's user avatar

Mr_and_Mrs_DMr_and_Mrs_D

31.2k37 gold badges175 silver badges355 bronze badges

2

Fixed my issue by writing print (sys.path) and found out that python was using out of date packages despite a clean install. Deleting these made python automatically use the correct packages.

answered Jul 21, 2016 at 18:51

dukevin's user avatar

dukevindukevin

22k36 gold badges80 silver badges110 bronze badges

In my case, because I’m using PyCharm and PyCharm create a ‘venv’ for every project in project folder, but it is only a mini env of python. Although you have installed the libraries you need in Python, but in your custom project ‘venv’, it is not available. This is the real reason of ‘ImportError: No module named xxxxxx’ occurred in PyCharm.
To resolve this issue, you must add libraries to your project custom env by these steps:

  • In PyCharm, from menu ‘File’->Settings
  • In Settings dialog, Project: XXXProject->Project Interpreter
  • Click «Add» button, it will show you ‘Available Packages’ dialog
  • Search your library, click ‘Install Package’
  • Then, all you needed package will be installed in you project custom ‘venv’ folder.

Settings dialog

Enjoy.

answered Feb 18, 2019 at 3:35

Yuanhui's user avatar

YuanhuiYuanhui

4595 silver badges15 bronze badges

Linux: Imported modules are located in /usr/local/lib/python2.7/dist-packages

If you’re using a module compiled in C, don’t forget to chmod the .so file after sudo setup.py install.

sudo chmod 755 /usr/local/lib/python2.7/dist-packages/*.so

answered May 30, 2014 at 22:50

KrisWebDev's user avatar

KrisWebDevKrisWebDev

9,2324 gold badges38 silver badges59 bronze badges

0

In my case, the problem was I was linking to debug python & boost::Python, which requires that the extension be FooLib_d.pyd, not just FooLib.pyd; renaming the file or updating CMakeLists.txt properties fixed the error.

Peter Mortensen's user avatar

answered Sep 4, 2013 at 2:52

peter karasev's user avatar

peter karasevpeter karasev

2,5281 gold badge28 silver badges38 bronze badges

My problem was that I added the directory with the __init__.py file to PYTHONPATH, when actually I needed to add its parent directory.

answered Mar 27, 2018 at 12:41

Rich's user avatar

RichRich

6421 gold badge6 silver badges14 bronze badges

0

If you are using a setup script/utility (e.g. setuptools) to deploy your package, don’t forget to add the respective files/modules to the installer.


When supported, use find_packages() or similar to automatically add new packages to the setup script. This will absolutely save you from a headache, especially if you put your project aside for some time and then add something later on.

import setuptools

setuptools.setup(
    name="example-pkg",
    version="0.0.1",
    author="Example Author",
    author_email="author@example.com",
    description="A small example package",
    packages=setuptools.find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3",
        "Operating System :: OS Independent",
    ],
    python_requires='>=3.6',
)

(Example taken from setuptools documentation)

answered Oct 17, 2020 at 11:36

michael-slx's user avatar

michael-slxmichael-slx

6558 silver badges15 bronze badges

For me, running the file as a module helped.

Instead of

python myapp/app.py

using

python -m myapp.app

It’s not exactly the same but it might be a better approach in some cases.

answered Apr 28, 2022 at 13:59

juanignaciosl's user avatar

juanignaciosljuanignaciosl

3,3952 gold badges26 silver badges28 bronze badges

I had the same problem (Python 2.7 Linux), I have found the solution and i would like to share it. In my case i had the structure below:

Booklet
-> __init__.py
-> Booklet.py
-> Question.py
default
-> __init_.py
-> main.py

In ‘main.py’ I had tried unsuccessfully all the combinations bellow:

from Booklet import Question
from Question import Question
from Booklet.Question import Question
from Booklet.Question import *
import Booklet.Question
# and many othet various combinations ...

The solution was much more simple than I thought. I renamed the folder «Booklet» into «booklet» and that’s it. Now Python can import the class Question normally by using in ‘main.py’ the code:

from booklet.Booklet import Booklet
from booklet.Question import Question
from booklet.Question import AnotherClass

From this I can conclude that Package-Names (folders) like ‘booklet’ must start from lower-case, else Python confuses it with Class names and Filenames.

Apparently, this was not your problem, but John Fouhy’s answer is very good and this thread has almost anything that can cause this issue. So, this is one more thing and I hope that maybe this could help others.

answered May 27, 2018 at 23:49

ioaniatr's user avatar

ioaniatrioaniatr

2774 silver badges15 bronze badges

In linux server try dos2unix script_name

(remove all (if there is any) pyc files with command find . -name '*.pyc' -delete)

and re run in the case if you worked on script on windows

answered Jan 17, 2020 at 15:07

Poli's user avatar

PoliPoli

7710 bronze badges

In my case, I was using sys.path.insert() to import a local module and was getting module not found from a different library. I had to put sys.path.insert() below the imports that reported module not found. I guess the best practice is to put sys.path.insert() at the bottom of your imports.

answered Mar 10, 2020 at 9:55

Michał Zawadzki's user avatar

I’ve found that changing the name (via GUI) of aliased folders (Mac) can cause issues with loading modules. If the original folder name is changed, remake the symbolic link. I’m unsure how prevalent this behavior may be, but it was frustrating to debug.

answered Feb 17, 2021 at 18:47

Ghoti's user avatar

GhotiGhoti

7374 silver badges18 bronze badges

another cause makes this issue

file.py

#!/bin/python
from bs4 import BeautifulSoup
  • if your default python is pyyhon2
$ file $(which python)
/sbin/python: symbolic link to python2
  • file.py need python3, for this case(bs4)
  • you can not execute this module with python2 like this:
$ python file.py
# or
$ file.py
# or
$ file.py # if locate in $PATH
  • Tow way to fix this error,
# should be to make python3 as default by symlink
$ rm $(which python) && ln -s $(which python3) /usr/bin/python
# or use alias
alias python='/usr/bin.../python3'

or change shebang in file.py to

#!/usr/bin/...python3

answered Aug 2, 2022 at 23:05

nextloop's user avatar

After just suffering the same issue I found my resolution was to delete all pyc files from my project, it seems like these cached files were somehow causing this error.

Easiest way I found to do this was to navigate to my project folder in Windows explorer and searching for *.pyc, then selecting all (Ctrl+A) and deleting them (Ctrl+X).

Its possible I could have resolved my issues by just deleting the specific pyc file but I never tried this

sina72's user avatar

sina72

4,8413 gold badges34 silver badges36 bronze badges

answered Aug 8, 2014 at 8:36

Sayse's user avatar

SayseSayse

42.2k14 gold badges77 silver badges143 bronze badges

0

I faced the same problem: Import error. In addition the library’ve been installed 100% correctly. The source of the problem was that on my PC 3 version of python (anaconda packet) have been installed). This is why the library was installed no to the right place. After that I just changed to the proper version of python in the my IDE PyCharm.

answered Dec 5, 2015 at 7:21

Rocketq's user avatar

RocketqRocketq

5,01420 gold badges75 silver badges123 bronze badges

I had the same error. It was caused by somebody creating a folder in the same folder as my script, the name of which conflicted with a module I was importing from elsewhere. Instead of importing the external module, it looked inside this folder which obviously didn’t contain the expected modules.

answered Dec 13, 2016 at 11:45

Toivo Säwén's user avatar

Toivo SäwénToivo Säwén

1,6732 gold badges14 silver badges33 bronze badges

Python is installed in a local directory.

My directory tree looks like this:

(local directory)/site-packages/toolkit/interface.py

My code is in here:

(local directory)/site-packages/toolkit/examples/mountain.py

To run the example, I write python mountain.py, and in the code I have:

from toolkit.interface import interface

And I get the error:

Traceback (most recent call last):
  File "mountain.py", line 28, in ?
    from toolkit.interface import interface
ImportError: No module named toolkit.interface

I have already checked sys.path and there I have the directory /site-packages. Also, I have the file __init__.py.bin in the toolkit folder to indicate to Python that this is a package. I also have a __init__.py.bin in the examples directory.

I do not know why Python cannot find the file when it is in sys.path. Any ideas? Can it be a permissions problem? Do I need some execution permission?

alex's user avatar

alex

6,3319 gold badges50 silver badges102 bronze badges

asked Dec 3, 2008 at 21:26

Eduardo's user avatar

7

Based on your comments to orip’s post, I guess this is what happened:

  1. You edited __init__.py on windows.
  2. The windows editor added something non-printing, perhaps a carriage-return (end-of-line in Windows is CR/LF; in unix it is LF only), or perhaps a CTRL-Z (windows end-of-file).
  3. You used WinSCP to copy the file to your unix box.
  4. WinSCP thought: «This has something that’s not basic text; I’ll put a .bin extension to indicate binary data.»
  5. The missing __init__.py (now called __init__.py.bin) means python doesn’t understand toolkit as a package.
  6. You create __init__.py in the appropriate directory and everything works… ?

answered Dec 4, 2008 at 0:17

John Fouhy's user avatar

John FouhyJohn Fouhy

40.5k19 gold badges62 silver badges77 bronze badges

8

Does

(local directory)/site-packages/toolkit

have a __init__.py?

To make import walk through your directories every directory must have a __init__.py file.

answered Dec 3, 2008 at 21:50

igorgue's user avatar

igorgueigorgue

17.6k13 gold badges37 silver badges52 bronze badges

2

I ran into something very similar when I did this exercise in LPTHW; I could never get Python to recognise that I had files in the directory I was calling from. But I was able to get it to work in the end. What I did, and what I recommend, is to try this:

(NOTE: From your initial post, I am assuming you are using an *NIX-based machine and are running things from the command line, so this advice is tailored to that. Since I run Ubuntu, this is what I did)

  1. Change directory (cd) to the directory above the directory where your files are. In this case, you’re trying to run the mountain.py file, and trying to call the toolkit.interface.py module, which are in separate directories. In this case, you would go to the directory that contains paths to both those files (or in other words, the closest directory that the paths of both those files share). Which in this case is the toolkit directory.

  2. When you are in the toolkit directory, enter this line of code on your command line:

    export PYTHONPATH=.

    This sets your PYTHONPATH to «.», which basically means that your PYTHONPATH will now look for any called files within the directory you are currently in, (and more to the point, in the sub-directory branches of the directory you are in. So it doesn’t just look in your current directory, but in all the directories that are in your current directory).

  3. After you’ve set your PYTHONPATH in the step above, run your module from your current directory (the toolkit directory). Python should now find and load the modules you specified.

user's user avatar

user

4,8906 gold badges17 silver badges35 bronze badges

answered Apr 22, 2014 at 3:52

Specterace's user avatar

SpecteraceSpecterace

1,0057 silver badges7 bronze badges

4

On *nix, also make sure that PYTHONPATH is configured correctly, especially that it has this format:

 .:/usr/local/lib/python

(Mind the .: at the beginning, so that it can search on the current directory, too.)

It may also be in other locations, depending on the version:

 .:/usr/lib/python
 .:/usr/lib/python2.6
 .:/usr/lib/python2.7 and etc.

Peter Mortensen's user avatar

answered Mar 4, 2011 at 21:14

Renaud's user avatar

RenaudRenaud

15.7k6 gold badges79 silver badges78 bronze badges

6

You are reading this answer says that your __init__.py is in the right place, you have installed all the dependencies and you are still getting the ImportError.

I was facing a similar issue except that my program would run fine when ran using PyCharm but the above error when I would run it from the terminal. After digging further, I found out that PYTHONPATH didn’t have the entry for the project directory. So, I set PYTHONPATH per Import statement works on PyCharm but not from terminal:

export PYTHONPATH=$PYTHONPATH:`pwd`  (OR your project root directory)

There’s another way to do this using sys.path as:

import sys
sys.path.insert(0,'<project directory>') OR
sys.path.append('<project directory>')

You can use insert/append based on the order in which you want your project to be searched.

jww's user avatar

jww

95k88 gold badges397 silver badges861 bronze badges

answered Feb 8, 2019 at 16:57

avp's user avatar

avpavp

2,76228 silver badges33 bronze badges

4

Using PyCharm (part of the JetBrains suite) you need to define your script directory as Source:
Right Click > Mark Directory as > Sources Root

answered Jan 4, 2017 at 17:53

MonoThreaded's user avatar

MonoThreadedMonoThreaded

11.2k11 gold badges69 silver badges100 bronze badges

2

For me, it was something really stupid. I installed the library using pip3 install but was running my program as python program.py as opposed to python3 program.py.

Nicolas Gervais's user avatar

answered Aug 22, 2019 at 16:02

kev's user avatar

kevkev

2,6513 gold badges21 silver badges45 bronze badges

1

I solved my own problem, and I will write a summary of the things that were wrong and the solution:

The file needs to be called exactly __init__.py. If the extension is different such as in my case .py.bin then Python cannot move through the directories and then it cannot find the modules. To edit the files you need to use a Linux editor, such as vi or nano. If you use a Windows editor this will write some hidden characters.

Another problem that was affecting it was that I had another Python version installed by the root, so if someone is working with a local installation of python, be sure that the Python installation that is running the programs is the local Python. To check this, just do which python, and see if the executable is the one that is in your local directory. If not, change the path, but be sure that the local Python directory is before than the other Python.

Peter Mortensen's user avatar

answered Dec 4, 2008 at 1:11

Eduardo's user avatar

EduardoEduardo

19.4k22 gold badges63 silver badges73 bronze badges

3

To mark a directory as a package you need a file named __init__.py, does this help?

answered Dec 3, 2008 at 21:31

orip's user avatar

oriporip

71.9k21 gold badges118 silver badges147 bronze badges

8

an easy solution is to install the module using python -m pip install <library-name> instead of pip install <library-name>
you may use sudo in case of admin restrictions

answered Sep 18, 2017 at 15:30

Badr Bellaj's user avatar

Badr BellajBadr Bellaj

10.6k2 gold badges40 silver badges40 bronze badges

3

To all those who still have this issue. I believe Pycharm gets confused with imports. For me, when i write ‘from namespace import something’, the previous line gets underlined in red, signaling that there is an error, but works. However »from .namespace import something’ doesn’t get underlined, but also doesn’t work.

Try

try:
    from namespace import something 
except NameError:
    from .namespace import something

answered May 11, 2019 at 19:34

AKJ's user avatar

AKJAKJ

8522 gold badges13 silver badges18 bronze badges

1

Yup. You need the directory to contain the __init__.py file, which is the file that initializes the package. Here, have a look at this.

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.

Raphael Schweikert's user avatar

answered Jan 7, 2009 at 14:22

miya's user avatar

miyamiya

1,0591 gold badge11 silver badges20 bronze badges

If you have tried all methods provided above but failed, maybe your module has the same name as a built-in module. Or, a module with the same name existing in a folder that has a high priority in sys.path than your module’s.

To debug, say your from foo.bar import baz complaints ImportError: No module named bar. Changing to import foo; print foo, which will show the path of foo. Is it what you expect?

If not, Either rename foo or use absolute imports.

answered May 2, 2017 at 6:41

liushuaikobe's user avatar

liushuaikobeliushuaikobe

2,1221 gold badge23 silver badges26 bronze badges

1

  1. You must have the file __ init__.py in the same directory where it’s the file that you are importing.
  2. You can not try to import a file that has the same name and be a file from 2 folders configured on the PYTHONPATH.

eg:
/etc/environment

PYTHONPATH=$PYTHONPATH:/opt/folder1:/opt/folder2

/opt/folder1/foo

/opt/folder2/foo

And, if you are trying to import foo file, python will not know which one you want.

from foo import … >>> importerror: no module named foo

answered Jan 9, 2014 at 19:45

Iasmini Gomes's user avatar

Iasmini GomesIasmini Gomes

6671 gold badge8 silver badges14 bronze badges

0

My two cents:

enter image description here

Spit:

Traceback (most recent call last):
      File "bashbash.py", line 454, in main
        import bosh
      File "Wrye Bash Launcher.pyw", line 63, in load_module
        mod = imp.load_source(fullname,filename+ext,fp)
      File "bashbosh.py", line 69, in <module>
        from game.oblivion.RecordGroups import MobWorlds, MobDials, MobICells, 
    ImportError: No module named RecordGroups

This confused the hell out of me — went through posts and posts suggesting ugly syspath hacks (as you see my __init__.py were all there). Well turns out that game/oblivion.py and game/oblivion was confusing python
which spit out the rather unhelpful «No module named RecordGroups». I’d be interested in a workaround and/or links documenting this (same name) behavior -> EDIT (2017.01.24) — have a look at What If I Have a Module and a Package With The Same Name? Interestingly normally packages take precedence but apparently our launcher violates this.

EDIT (2015.01.17): I did not mention we use a custom launcher dissected here.

Community's user avatar

answered Sep 6, 2014 at 11:17

Mr_and_Mrs_D's user avatar

Mr_and_Mrs_DMr_and_Mrs_D

31.2k37 gold badges175 silver badges355 bronze badges

2

Fixed my issue by writing print (sys.path) and found out that python was using out of date packages despite a clean install. Deleting these made python automatically use the correct packages.

answered Jul 21, 2016 at 18:51

dukevin's user avatar

dukevindukevin

22k36 gold badges80 silver badges110 bronze badges

In my case, because I’m using PyCharm and PyCharm create a ‘venv’ for every project in project folder, but it is only a mini env of python. Although you have installed the libraries you need in Python, but in your custom project ‘venv’, it is not available. This is the real reason of ‘ImportError: No module named xxxxxx’ occurred in PyCharm.
To resolve this issue, you must add libraries to your project custom env by these steps:

  • In PyCharm, from menu ‘File’->Settings
  • In Settings dialog, Project: XXXProject->Project Interpreter
  • Click «Add» button, it will show you ‘Available Packages’ dialog
  • Search your library, click ‘Install Package’
  • Then, all you needed package will be installed in you project custom ‘venv’ folder.

Settings dialog

Enjoy.

answered Feb 18, 2019 at 3:35

Yuanhui's user avatar

YuanhuiYuanhui

4595 silver badges15 bronze badges

Linux: Imported modules are located in /usr/local/lib/python2.7/dist-packages

If you’re using a module compiled in C, don’t forget to chmod the .so file after sudo setup.py install.

sudo chmod 755 /usr/local/lib/python2.7/dist-packages/*.so

answered May 30, 2014 at 22:50

KrisWebDev's user avatar

KrisWebDevKrisWebDev

9,2324 gold badges38 silver badges59 bronze badges

0

In my case, the problem was I was linking to debug python & boost::Python, which requires that the extension be FooLib_d.pyd, not just FooLib.pyd; renaming the file or updating CMakeLists.txt properties fixed the error.

Peter Mortensen's user avatar

answered Sep 4, 2013 at 2:52

peter karasev's user avatar

peter karasevpeter karasev

2,5281 gold badge28 silver badges38 bronze badges

My problem was that I added the directory with the __init__.py file to PYTHONPATH, when actually I needed to add its parent directory.

answered Mar 27, 2018 at 12:41

Rich's user avatar

RichRich

6421 gold badge6 silver badges14 bronze badges

0

If you are using a setup script/utility (e.g. setuptools) to deploy your package, don’t forget to add the respective files/modules to the installer.


When supported, use find_packages() or similar to automatically add new packages to the setup script. This will absolutely save you from a headache, especially if you put your project aside for some time and then add something later on.

import setuptools

setuptools.setup(
    name="example-pkg",
    version="0.0.1",
    author="Example Author",
    author_email="author@example.com",
    description="A small example package",
    packages=setuptools.find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3",
        "Operating System :: OS Independent",
    ],
    python_requires='>=3.6',
)

(Example taken from setuptools documentation)

answered Oct 17, 2020 at 11:36

michael-slx's user avatar

michael-slxmichael-slx

6558 silver badges15 bronze badges

For me, running the file as a module helped.

Instead of

python myapp/app.py

using

python -m myapp.app

It’s not exactly the same but it might be a better approach in some cases.

answered Apr 28, 2022 at 13:59

juanignaciosl's user avatar

juanignaciosljuanignaciosl

3,3952 gold badges26 silver badges28 bronze badges

I had the same problem (Python 2.7 Linux), I have found the solution and i would like to share it. In my case i had the structure below:

Booklet
-> __init__.py
-> Booklet.py
-> Question.py
default
-> __init_.py
-> main.py

In ‘main.py’ I had tried unsuccessfully all the combinations bellow:

from Booklet import Question
from Question import Question
from Booklet.Question import Question
from Booklet.Question import *
import Booklet.Question
# and many othet various combinations ...

The solution was much more simple than I thought. I renamed the folder «Booklet» into «booklet» and that’s it. Now Python can import the class Question normally by using in ‘main.py’ the code:

from booklet.Booklet import Booklet
from booklet.Question import Question
from booklet.Question import AnotherClass

From this I can conclude that Package-Names (folders) like ‘booklet’ must start from lower-case, else Python confuses it with Class names and Filenames.

Apparently, this was not your problem, but John Fouhy’s answer is very good and this thread has almost anything that can cause this issue. So, this is one more thing and I hope that maybe this could help others.

answered May 27, 2018 at 23:49

ioaniatr's user avatar

ioaniatrioaniatr

2774 silver badges15 bronze badges

In linux server try dos2unix script_name

(remove all (if there is any) pyc files with command find . -name '*.pyc' -delete)

and re run in the case if you worked on script on windows

answered Jan 17, 2020 at 15:07

Poli's user avatar

PoliPoli

7710 bronze badges

In my case, I was using sys.path.insert() to import a local module and was getting module not found from a different library. I had to put sys.path.insert() below the imports that reported module not found. I guess the best practice is to put sys.path.insert() at the bottom of your imports.

answered Mar 10, 2020 at 9:55

Michał Zawadzki's user avatar

I’ve found that changing the name (via GUI) of aliased folders (Mac) can cause issues with loading modules. If the original folder name is changed, remake the symbolic link. I’m unsure how prevalent this behavior may be, but it was frustrating to debug.

answered Feb 17, 2021 at 18:47

Ghoti's user avatar

GhotiGhoti

7374 silver badges18 bronze badges

another cause makes this issue

file.py

#!/bin/python
from bs4 import BeautifulSoup
  • if your default python is pyyhon2
$ file $(which python)
/sbin/python: symbolic link to python2
  • file.py need python3, for this case(bs4)
  • you can not execute this module with python2 like this:
$ python file.py
# or
$ file.py
# or
$ file.py # if locate in $PATH
  • Tow way to fix this error,
# should be to make python3 as default by symlink
$ rm $(which python) && ln -s $(which python3) /usr/bin/python
# or use alias
alias python='/usr/bin.../python3'

or change shebang in file.py to

#!/usr/bin/...python3

answered Aug 2, 2022 at 23:05

nextloop's user avatar

After just suffering the same issue I found my resolution was to delete all pyc files from my project, it seems like these cached files were somehow causing this error.

Easiest way I found to do this was to navigate to my project folder in Windows explorer and searching for *.pyc, then selecting all (Ctrl+A) and deleting them (Ctrl+X).

Its possible I could have resolved my issues by just deleting the specific pyc file but I never tried this

sina72's user avatar

sina72

4,8413 gold badges34 silver badges36 bronze badges

answered Aug 8, 2014 at 8:36

Sayse's user avatar

SayseSayse

42.2k14 gold badges77 silver badges143 bronze badges

0

I faced the same problem: Import error. In addition the library’ve been installed 100% correctly. The source of the problem was that on my PC 3 version of python (anaconda packet) have been installed). This is why the library was installed no to the right place. After that I just changed to the proper version of python in the my IDE PyCharm.

answered Dec 5, 2015 at 7:21

Rocketq's user avatar

RocketqRocketq

5,01420 gold badges75 silver badges123 bronze badges

I had the same error. It was caused by somebody creating a folder in the same folder as my script, the name of which conflicted with a module I was importing from elsewhere. Instead of importing the external module, it looked inside this folder which obviously didn’t contain the expected modules.

answered Dec 13, 2016 at 11:45

Toivo Säwén's user avatar

Toivo SäwénToivo Säwén

1,6732 gold badges14 silver badges33 bronze badges

I’m having a hard time understanding how module importing works in Python (I’ve never done it in any other language before either).

Let’s say I have:

myapp/__init__.py
myapp/myapp/myapp.py
myapp/myapp/SomeObject.py
myapp/tests/TestCase.py

Now I’m trying to get something like this:

myapp.py
===================
from myapp import SomeObject
# stuff ...

TestCase.py
===================
from myapp import SomeObject
# some tests on SomeObject

However, I’m definitely doing something wrong as Python can’t see that myapp is a module:

ImportError: No module named myapp

asked Feb 21, 2012 at 18:27

1

In your particular case it looks like you’re trying to import SomeObject from the myapp.py and TestCase.py scripts. From myapp.py, do

import SomeObject

since it is in the same folder. For TestCase.py, do

from ..myapp import SomeObject

However, this will work only if you are importing TestCase from the package. If you want to directly run python TestCase.py, you would have to mess with your path. This can be done within Python:

import sys
sys.path.append("..")
from myapp import SomeObject

though that is generally not recommended.

In general, if you want other people to use your Python package, you should use distutils to create a setup script. That way, anyone can install your package easily using a command like python setup.py install and it will be available everywhere on their machine. If you’re serious about the package, you could even add it to the Python Package Index, PyPI.

answered Feb 21, 2012 at 18:46

David Robinson's user avatar

David RobinsonDavid Robinson

76.3k16 gold badges163 silver badges183 bronze badges

6

The function import looks for files into your PYTHONPATH env. variable and your local directory. So you can either put all your files in the same directory, or export the path typing into a terminal::

export PYTHONPATH="$PYTHONPATH:/path_to_myapp/myapp/myapp/"

Michael's user avatar

Michael

1,7352 gold badges19 silver badges30 bronze badges

answered Feb 21, 2012 at 18:31

Zenon's user avatar

ZenonZenon

1,46113 silver badges21 bronze badges

4

exporting path is a good way. Another way is to add a .pth to your site-packages location.
On my mac my python keeps site-packages in /Library/Python shown below

/Library/Python/2.7/site-packages

I created a file called awesome.pth at /Library/Python/2.7/site-packages/awesome.pth and in the file put the following path that references my awesome modules

/opt/awesome/custom_python_modules

answered May 20, 2013 at 23:36

jmontross's user avatar

jmontrossjmontross

3,4931 gold badge21 silver badges17 bronze badges

4

You can try

from myapp.myapp import SomeObject

because your project name is the same as the myapp.py which makes it search the project document first

answered Mar 6, 2017 at 13:54

阿东刘's user avatar

阿东刘阿东刘

1391 silver badge2 bronze badges

You need to have

__init__.py

in all the folders that have code you need to interact with.
You also need to specify the top folder name of your project in every import even if the file you tried to import is at the same level.

answered Jun 5, 2020 at 15:42

Krysalead's user avatar

KrysaleadKrysalead

811 silver badge1 bronze badge

In your first myapp directory ,u can add a setup.py file and add two python code in setup.py

from setuptools import setup
setup(name='myapp')

in your first myapp directory in commandline , use pip install -e . to install the package

answered Oct 28, 2017 at 11:30

未来陆家嘴顶尖的投资人's user avatar

未来陆家嘴顶尖的投资人未来陆家嘴顶尖的投资人

1,71820 silver badges19 bronze badges

pip install on Windows 10 defaults to installing in ‘Program Files/PythonXX/Lib/site-packages’ which is a directory that requires administrative privileges. So I fixed my issue by running pip install as Administrator (you have to open command prompt as administrator even if you are logged in with an admin account). Also, it is safer to call pip from python.
e.g.
python -m pip install <package-name>
instead of
pip install <package-name>

answered Aug 21, 2018 at 9:12

sziraqui's user avatar

sziraquisziraqui

5,6333 gold badges27 silver badges37 bronze badges

1

In my case it was Windows vs Python surprise, despite Windows filenames are not case sensitive, Python import is. So if you have Stuff.py file you need to import this name as-is.

answered May 17, 2018 at 9:31

astrowalker's user avatar

astrowalkerastrowalker

2,9852 gold badges16 silver badges36 bronze badges

let’s say i write a module

import os
my_home_dir=os.environ['HOME'] // in windows 'HOMEPATH'
file_abs_path=os.path.join(my_home_dir,"my_module.py")

with open(file_abs_path,"w") as f:
   f.write("print('I am loaded successfully')")

import importlib
importlib.util.find_spec('my_module') ==> cannot find

we have to tell python where to look for the module. we have to add our path to the sys.path

 import sys
 sys.path.append(file_abs_path)

now importlib.util.find_spec('my_module') returns:

  ModuleSpec(name='my_module', loader=<_frozen_importlib_external.SourceFileLoader object at 0x7fa40143e8e0>, origin='/Users/name/my_module.py')

we created our module, we informed python its path, now we should be able to import it

 import my_module

//I am loaded successfully

answered Sep 14, 2020 at 2:09

Yilmaz's user avatar

YilmazYilmaz

26k10 gold badges130 silver badges162 bronze badges

0

This worked for me:

from .myapp import SomeObject

The . signifies that it will search any local modules from the parent module.

answered May 30, 2022 at 3:58

Evan Schwartzentruber's user avatar

Short Answer:

python -m ParentPackage.Submodule

Executing the required file via module flag worked for me. Lets say we got a typical directory structure as below:

my_project:
 | Core
    ->myScript.py
 | Utils
   ->helpers.py
 configs.py

Now if you want to run a file inside a directory, that has imports from other modules, all you need to do is like below:

python -m Core.myscript

PS: You gotta use dot notation to refer the submodules(Files/scripts you want to execute). Also I used python3.9+. So I didnt require neither any init.py nor any sys path append statements.

Hope that helps! Happy Coding!

answered Aug 29, 2021 at 13:23

Deekshith Anand's user avatar

Deekshith AnandDeekshith Anand

1,8151 gold badge19 silver badges21 bronze badges

If you use Anaconda you can do:

conda develop /Path/To/Your/Modules

from the Shell and it will write your path into a conda.pth file into the standard directory for 3rd party modules (site-packages in my case).

answered Aug 5, 2022 at 21:39

Alexander Audet's user avatar

If you are using the IPython Console, make sure your IDE (e.g., spyder) is pointing to the right working directory (i.e., your project folder)

answered Nov 18, 2022 at 15:16

Mehdi Boukhechba's user avatar

Mehdi BoukhechbaMehdi Boukhechba

2,4432 gold badges19 silver badges24 bronze badges

Besides the suggested solutions like the accepted answer, I had the same problem in Pycharm, and I didn’t want to modify imports like the relative addressing suggested above.

I finally found out that if I mark my src/ (root directory of my python codes) as the source in Interpreter settings, the issue will be resolved.

In the settings

enter image description here

answered Dec 25, 2022 at 13:57

AMK's user avatar

AMKAMK

4624 silver badges15 bronze badges

I’m having a hard time understanding how module importing works in Python (I’ve never done it in any other language before either).

Let’s say I have:

myapp/__init__.py
myapp/myapp/myapp.py
myapp/myapp/SomeObject.py
myapp/tests/TestCase.py

Now I’m trying to get something like this:

myapp.py
===================
from myapp import SomeObject
# stuff ...

TestCase.py
===================
from myapp import SomeObject
# some tests on SomeObject

However, I’m definitely doing something wrong as Python can’t see that myapp is a module:

ImportError: No module named myapp

asked Feb 21, 2012 at 18:27

1

In your particular case it looks like you’re trying to import SomeObject from the myapp.py and TestCase.py scripts. From myapp.py, do

import SomeObject

since it is in the same folder. For TestCase.py, do

from ..myapp import SomeObject

However, this will work only if you are importing TestCase from the package. If you want to directly run python TestCase.py, you would have to mess with your path. This can be done within Python:

import sys
sys.path.append("..")
from myapp import SomeObject

though that is generally not recommended.

In general, if you want other people to use your Python package, you should use distutils to create a setup script. That way, anyone can install your package easily using a command like python setup.py install and it will be available everywhere on their machine. If you’re serious about the package, you could even add it to the Python Package Index, PyPI.

answered Feb 21, 2012 at 18:46

David Robinson's user avatar

David RobinsonDavid Robinson

76.3k16 gold badges163 silver badges183 bronze badges

6

The function import looks for files into your PYTHONPATH env. variable and your local directory. So you can either put all your files in the same directory, or export the path typing into a terminal::

export PYTHONPATH="$PYTHONPATH:/path_to_myapp/myapp/myapp/"

Michael's user avatar

Michael

1,7352 gold badges19 silver badges30 bronze badges

answered Feb 21, 2012 at 18:31

Zenon's user avatar

ZenonZenon

1,46113 silver badges21 bronze badges

4

exporting path is a good way. Another way is to add a .pth to your site-packages location.
On my mac my python keeps site-packages in /Library/Python shown below

/Library/Python/2.7/site-packages

I created a file called awesome.pth at /Library/Python/2.7/site-packages/awesome.pth and in the file put the following path that references my awesome modules

/opt/awesome/custom_python_modules

answered May 20, 2013 at 23:36

jmontross's user avatar

jmontrossjmontross

3,4931 gold badge21 silver badges17 bronze badges

4

You can try

from myapp.myapp import SomeObject

because your project name is the same as the myapp.py which makes it search the project document first

answered Mar 6, 2017 at 13:54

阿东刘's user avatar

阿东刘阿东刘

1391 silver badge2 bronze badges

You need to have

__init__.py

in all the folders that have code you need to interact with.
You also need to specify the top folder name of your project in every import even if the file you tried to import is at the same level.

answered Jun 5, 2020 at 15:42

Krysalead's user avatar

KrysaleadKrysalead

811 silver badge1 bronze badge

In your first myapp directory ,u can add a setup.py file and add two python code in setup.py

from setuptools import setup
setup(name='myapp')

in your first myapp directory in commandline , use pip install -e . to install the package

answered Oct 28, 2017 at 11:30

未来陆家嘴顶尖的投资人's user avatar

未来陆家嘴顶尖的投资人未来陆家嘴顶尖的投资人

1,71820 silver badges19 bronze badges

pip install on Windows 10 defaults to installing in ‘Program Files/PythonXX/Lib/site-packages’ which is a directory that requires administrative privileges. So I fixed my issue by running pip install as Administrator (you have to open command prompt as administrator even if you are logged in with an admin account). Also, it is safer to call pip from python.
e.g.
python -m pip install <package-name>
instead of
pip install <package-name>

answered Aug 21, 2018 at 9:12

sziraqui's user avatar

sziraquisziraqui

5,6333 gold badges27 silver badges37 bronze badges

1

In my case it was Windows vs Python surprise, despite Windows filenames are not case sensitive, Python import is. So if you have Stuff.py file you need to import this name as-is.

answered May 17, 2018 at 9:31

astrowalker's user avatar

astrowalkerastrowalker

2,9852 gold badges16 silver badges36 bronze badges

let’s say i write a module

import os
my_home_dir=os.environ['HOME'] // in windows 'HOMEPATH'
file_abs_path=os.path.join(my_home_dir,"my_module.py")

with open(file_abs_path,"w") as f:
   f.write("print('I am loaded successfully')")

import importlib
importlib.util.find_spec('my_module') ==> cannot find

we have to tell python where to look for the module. we have to add our path to the sys.path

 import sys
 sys.path.append(file_abs_path)

now importlib.util.find_spec('my_module') returns:

  ModuleSpec(name='my_module', loader=<_frozen_importlib_external.SourceFileLoader object at 0x7fa40143e8e0>, origin='/Users/name/my_module.py')

we created our module, we informed python its path, now we should be able to import it

 import my_module

//I am loaded successfully

answered Sep 14, 2020 at 2:09

Yilmaz's user avatar

YilmazYilmaz

26k10 gold badges130 silver badges162 bronze badges

0

This worked for me:

from .myapp import SomeObject

The . signifies that it will search any local modules from the parent module.

answered May 30, 2022 at 3:58

Evan Schwartzentruber's user avatar

Short Answer:

python -m ParentPackage.Submodule

Executing the required file via module flag worked for me. Lets say we got a typical directory structure as below:

my_project:
 | Core
    ->myScript.py
 | Utils
   ->helpers.py
 configs.py

Now if you want to run a file inside a directory, that has imports from other modules, all you need to do is like below:

python -m Core.myscript

PS: You gotta use dot notation to refer the submodules(Files/scripts you want to execute). Also I used python3.9+. So I didnt require neither any init.py nor any sys path append statements.

Hope that helps! Happy Coding!

answered Aug 29, 2021 at 13:23

Deekshith Anand's user avatar

Deekshith AnandDeekshith Anand

1,8151 gold badge19 silver badges21 bronze badges

If you use Anaconda you can do:

conda develop /Path/To/Your/Modules

from the Shell and it will write your path into a conda.pth file into the standard directory for 3rd party modules (site-packages in my case).

answered Aug 5, 2022 at 21:39

Alexander Audet's user avatar

If you are using the IPython Console, make sure your IDE (e.g., spyder) is pointing to the right working directory (i.e., your project folder)

answered Nov 18, 2022 at 15:16

Mehdi Boukhechba's user avatar

Mehdi BoukhechbaMehdi Boukhechba

2,4432 gold badges19 silver badges24 bronze badges

Besides the suggested solutions like the accepted answer, I had the same problem in Pycharm, and I didn’t want to modify imports like the relative addressing suggested above.

I finally found out that if I mark my src/ (root directory of my python codes) as the source in Interpreter settings, the issue will be resolved.

In the settings

enter image description here

answered Dec 25, 2022 at 13:57

AMK's user avatar

AMKAMK

4624 silver badges15 bronze badges

Python ImportError

Introduction to Python ImportError

In Python, we use “import” when we want to import any specific module in the Python program. In Python, to make or to allow the module contents available to the program we use import statements. Therefore when importing any module and there is any trouble in importing modules to the program then there is a chance of ImportError occurrence. In this article, we will discuss such error which generally occurs if there is an invalid declaration of import statement for module importing and such problems also known as ModuleNotFoundError in the latest versions of Python such as 3.6 and newer versions.

Examples of ImporError in Python

In Python, when we want to include the module contents in the program then we have to import these specific modules in the program. So to do this we use “import” keyword such as import statement with the module name. When writing this statement and the specified module is not written properly or the imported module is not found in the Python library then the Python interpreter throws an error known as ImportError.

There are two conditions when the ImportError will be raised. They are

  • If the module does not exist.
  • If we are trying to import submodule from the module

Now let us demonstrate in the below program that throws an ImportError.

Example #1

Now suppose we are trying to import module “request” which is not present or saved in Python drive where we need to download it. Let us see a small example below:

import request

Output:

Python ImportError-1.1

In the above sample code, we can see that we are importing a module named “request” which is not present in the downloaded Python library. Therefore it throws an ImportError which gives the message saying no module named “request”. As each module when downloaded or inbuilt it has its own private symbol table where all defined module is saved by creating separate namespace. Therefore if the module is present then there is no occurrence of such error.

In Python, there is another way of importing modules in the program and if this statement also fails then also ImportError occurs. Let us see the example below:

Example #2

from crypt import pwd

Output:

Example-1.2

In the above program, we can see another way of importing modules. This also throws ImportError if the module is not present in the private Python library.

The above two methods of importing modules in the program throw an error if the module is not present. Therefore catch such errors in exception handling concept it provides an ImportError exception which has the Python exception hierarchy as BaseException, Exception, and then comes ImportError. In Python, even moduleNotFoundError is also the same as an ImportError exception. Now let us below how to handle such error in the Python program using try and except blocks of exception handling.

Example #3

print("Program to demonstrate to handle ImportError:")
print("n")
try:
from crypt import pwd
except ImportError as ie:
print("It cannot import module and submodule", ie)

Output:

Example-1.3

In the above program, we can see when we are trying to import the “crypt” module and we are handling this ImportError using try and except the block of exception handling. This is one way to avoid the error message to be printed.

To avoid such an ImportError exception we saw above the use of exception handling. But still, it will display the error message on the output screen. Such error occurs when there is no module present in the Python private table. To avoid this we can directly download this module from the Internet to the Python IDE. Let us see how we can avoid this ImportError we need to download the module and we will not get this error and this done as below:

pip install module_name

If pip is installed we can directly run this to install the module. Else first we need to install the pip and then install the other packages.

Another way to download the module is to download the package directly through the Internet by downloading the module and unzip the folder and save that folder where the Python software is saved.

Conclusion – Python ImportError

In this article, we conclude that the ImportError is an exception in Python hierarchy under BaseException, Exception, and then comes this Exception. In Python, ImportError occurs when the Python program tries to import module which does not exist in the private table. This exception can be avoided using exception handling using try and except blocks. We also saw examples of how the ImportError occurs and how it is handled.

Recommended Articles

This is a guide to Python ImportError. Here we also discuss the introduction and working of import error in python along with its different examples and its code implementation. You may also have a look at the following articles to learn more –

  1. Lambda in Python
  2. Finally in Python
  3. Python Empty List
  4. Python Iterator Dictionary 

Понравилась статья? Поделить с друзьями:
  • Import sqlalchemy error
  • Import seaborn as sns ошибка
  • Import requests python 3 ошибка
  • Import requests error
  • Import requests could not be resolved from source как исправить