I have a piece of code which is working in Linux, and I am now trying to run it in windows, I import sys but when I use sys.exit(). I get an error, sys is not defined. Here is the begining part of my code
try:
import numpy as np
import pyfits as pf
import scipy.ndimage as nd
import pylab as pl
import os
import heapq
import sys
from scipy.optimize import leastsq
except ImportError:
print "Error: missing one of the libraries (numpy, pyfits, scipy, matplotlib)"
sys.exit()
Why is sys not working??
svineet
1,8491 gold badge16 silver badges27 bronze badges
asked Jul 20, 2013 at 11:21
Move import sys outside of the try—except block:
import sys
try:
# ...
except ImportError:
# ...
If any of the imports before the import sys line fails, the rest of the block is not executed, and sys is never imported. Instead, execution jumps to the exception handling block, where you then try to access a non-existing name.
sys is a built-in module anyway, it is always present as it holds the data structures to track imports; if importing sys fails, you have bigger problems on your hand (as that would indicate that all module importing is broken).
answered Jul 20, 2013 at 11:23
Martijn Pieters♦Martijn Pieters
1.0m282 gold badges3963 silver badges3293 bronze badges
0
You’re trying to import all of those modules at once. Even if one of them fails, the rest will not import. For example:
try:
import datetime
import foo
import sys
except ImportError:
pass
Let’s say foo doesn’t exist. Then only datetime will be imported.
What you can do is import the sys module at the beginning of the file, before the try/except statement:
import sys
try:
import numpy as np
import pyfits as pf
import scipy.ndimage as nd
import pylab as pl
import os
import heapq
from scipy.optimize import leastsq
except ImportError:
print "Error: missing one of the libraries (numpy, pyfits, scipy, matplotlib)"
sys.exit()
answered Jul 20, 2013 at 11:24
![]()
TerryATerryA
57.9k11 gold badges118 silver badges140 bronze badges
0
I’m guessing your code failed BEFORE import sys, so it can’t find it when you handle the exception.
Also, you should indent the your code whithin the try block.
try:
import sys
# .. other safe imports
try:
import numpy as np
# other unsafe imports
except ImportError:
print "Error: missing one of the libraries (numpy, pyfits, scipy, matplotlib)"
sys.exit()
answered Jul 20, 2013 at 11:26
astrognocciastrognocci
1,0577 silver badges16 bronze badges
In addition to the answers given above, check the last line of the error message in your console. In my case, the ‘site-packages’ path in sys.path.append(‘…..’) was wrong.
answered Dec 12, 2020 at 17:19
![]()
Начал изучать Python по учебнику Лутц.М — изучаем Python. У меня установлен python 3.4.1.
Создал модуль с текстом:
import sys
print(sys.platform)
print(2 ** 100)
x = ‘Spam!’
print(x * 8)
Обозвал его script1 и дал расширение .Py.
Данный модуль закинул в корневую папку где установлен питон
По учебнику сказано — «Сохранив этот текстовый файл, вы сможете предложить интерпретатору Python выполнить его, указав полное имя файла в качестве первого аргументакоманды python, введя следующую строку в системной командной строке:
% python script1.py»
Следуя инструкции я получаю ошибку 
Среда Path у меня объявлена
Так почему же когда я ввожу python script1.py (как сказано в учебники) я не получаю нужного результата ?
-
Вопрос заданболее трёх лет назад
-
20075 просмотров
script1.py должен быть в текущей директории
или текущая директория должна быть там где script1.py (:
или указать полный путь до файла: python C:myprojectscript1.py
Пригласить эксперта
надо запускать в виде python -m script1 тогда срабатывает система поиска модулей пайтона по путям из sys.path
C:Usersusername>C:Python34python.exe -h
usage: C:Python34python.exe [option] … [-c cmd | -m mod | file | -] [arg] ..
если запускать как python script1.py то поиск будет осуществлятся через операционную систему, то есть в текущей директории.
Переменная окружения Path используется для поиска _выполняемых_ файлов, python.exe в твоем случае.
еще пожелание: для названий модулей и их расширения используйте только нижний регистр.
-
Показать ещё
Загружается…
28 янв. 2023, в 22:48
500 руб./за проект
28 янв. 2023, в 20:58
30000 руб./за проект
28 янв. 2023, в 20:46
50000 руб./за проект
Минуточку внимания
Порой бывает трудно правильно реализовать 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 3.3 любая папка (даже без
- Объект: в 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 ищет импортируемые модули:
- Модули стандартной библиотеки (например,
math,os). - Модули или пакеты, указанные в
sys.path:-
- Если интерпретатор Python запущен в интерактивном режиме:
sys.path[0]— пустая строка''. Это значит, что Python будет искать в текущей рабочей директории, из которой вы запустили интерпретатор. В Unix-системах эту директорию можно узнать с помощью командыpwd.
Если мы запускаем скрипт командой
python <script>.py:sys.path[0]— это путь к<script>.py.
- Директории, указанные в переменной среды
PYTHONPATH. - Директория по умолчанию, которая зависит от дистрибутива Python.
- Если интерпретатор 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 есть две функции:
- Превратить папку со скриптами в импортируемый пакет модулей (до Python 3.3).
- Выполнить код инициализации пакета.
Превращение папки со скриптами в импортируемый пакет модулей
Чтобы импортировать модуль (или пакет) из директории, которая находится не в директории нашего скрипта (или не в директории, из которой мы запускаем интерактивный интерпретатор), этот модуль должен быть в пакете.
Как было сказано ранее, любая директория, содержащая файл __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 разных вида импортов:
import <пакет>import <модуль>from <пакет> import <модуль или подпакет или объект>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 приведёт к ошибке, так как он ещё не был импортирован.
Абсолютный и относительный импорт
При абсолютном импорте используется полный путь (от начала корневой папки проекта) к желаемому модулю.
При относительном импорте используется относительный путь (начиная с пути текущего модуля) к желаемому модулю. Есть два типа относительных импортов:
- При явном импорте используется формат
from .<модуль/пакет> import X, где символы точки.показывают, на сколько директорий «вверх» нужно подняться. Одна точка.показывает текущую директорию, две точки..— на одну директорию выше и т. д. - Неявный относительный импорт пишется так, как если бы текущая директория была частью
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 напрямую, запустите его как импортируемый модуль, а не как скрипт:
- В консоли смените директорию на
test/. - Запустите
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. Они ещё раз изложены здесь наряду с менее важными отличиями:
- Python 2 поддерживает неявные относительные импорты, Python 3 — нет.
- В Python 2, чтобы папка считалась пакетом и её можно было импортировать, она должна содержать файл
__init__.py. С версии Python 3.3 благодаря введению неявных пакетов пространств имён все папки считаются пакетами вне зависимости от наличия__init__.py. - В 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
6,2929 gold badges49 silver badges102 bronze badges
asked Dec 3, 2008 at 21:26
7
Based on your comments to orip’s post, I guess this is what happened:
- You edited
__init__.pyon windows. - 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).
- You used WinSCP to copy the file to your unix box.
- WinSCP thought: «This has something that’s not basic text; I’ll put a .bin extension to indicate binary data.»
- The missing
__init__.py(now called__init__.py.bin) means python doesn’t understand toolkit as a package. - You create
__init__.pyin the appropriate directory and everything works… ?
answered Dec 4, 2008 at 0:17
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
![]()
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)
-
Change directory (cd) to the directory above the directory where your files are. In this case, you’re trying to run the
mountain.pyfile, and trying to call thetoolkit.interface.pymodule, 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 thetoolkitdirectory. -
When you are in the
toolkitdirectory, 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).
-
After you’ve set your PYTHONPATH in the step above, run your module from your current directory (the
toolkitdirectory). Python should now find and load the modules you specified.
![]()
user
3,8965 gold badges17 silver badges34 bronze badges
answered Apr 22, 2014 at 3:52
SpecteraceSpecterace
9956 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.
![]()
answered Mar 4, 2011 at 21:14
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
94.9k88 gold badges395 silver badges860 bronze badges
answered Feb 8, 2019 at 16:57
![]()
avpavp
2,71228 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
![]()
MonoThreadedMonoThreaded
11.1k11 gold badges68 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.
![]()
answered Aug 22, 2019 at 16:02
![]()
kevkev
2,6413 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.
![]()
answered Dec 4, 2008 at 1:11
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
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 BellajBadr Bellaj
10.5k2 gold badges39 silver badges39 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
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.
answered Jan 7, 2009 at 14:22
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
liushuaikobeliushuaikobe
2,1221 gold badge23 silver badges26 bronze badges
1
- You must have the file __ init__.py in the same directory where it’s the file that you are importing.
- 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 GomesIasmini Gomes
6571 gold badge8 silver badges14 bronze badges
0
My two cents:

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.
answered Sep 6, 2014 at 11:17
Mr_and_Mrs_DMr_and_Mrs_D
31.1k37 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
![]()
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.

Enjoy.
answered Feb 18, 2019 at 3:35
![]()
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
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.
![]()
answered Sep 4, 2013 at 2:52
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
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-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
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
![]()
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
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
![]()
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
![]()
GhotiGhoti
7374 silver badges18 bronze badges
another cause makes this issue
file.py
#!/bin/python
from bs4 import BeautifulSoup
- if your default
pythonispyyhon2
$ file $(which python)
/sbin/python: symbolic link to python2
file.pyneedpython3, for this case(bs4)- you can not execute this module with
python2like 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
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
4,8413 gold badges34 silver badges36 bronze badges
answered Aug 8, 2014 at 8:36
![]()
SayseSayse
42.2k14 gold badges77 silver badges142 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
![]()
RocketqRocketq
5,00420 gold badges75 silver badges122 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énToivo Säwén
1,6632 gold badges14 silver badges32 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
6,2929 gold badges49 silver badges102 bronze badges
asked Dec 3, 2008 at 21:26
7
Based on your comments to orip’s post, I guess this is what happened:
- You edited
__init__.pyon windows. - 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).
- You used WinSCP to copy the file to your unix box.
- WinSCP thought: «This has something that’s not basic text; I’ll put a .bin extension to indicate binary data.»
- The missing
__init__.py(now called__init__.py.bin) means python doesn’t understand toolkit as a package. - You create
__init__.pyin the appropriate directory and everything works… ?
answered Dec 4, 2008 at 0:17
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
![]()
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)
-
Change directory (cd) to the directory above the directory where your files are. In this case, you’re trying to run the
mountain.pyfile, and trying to call thetoolkit.interface.pymodule, 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 thetoolkitdirectory. -
When you are in the
toolkitdirectory, 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).
-
After you’ve set your PYTHONPATH in the step above, run your module from your current directory (the
toolkitdirectory). Python should now find and load the modules you specified.
![]()
user
3,8965 gold badges17 silver badges34 bronze badges
answered Apr 22, 2014 at 3:52
SpecteraceSpecterace
9956 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.
![]()
answered Mar 4, 2011 at 21:14
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
94.9k88 gold badges395 silver badges860 bronze badges
answered Feb 8, 2019 at 16:57
![]()
avpavp
2,71228 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
![]()
MonoThreadedMonoThreaded
11.1k11 gold badges68 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.
![]()
answered Aug 22, 2019 at 16:02
![]()
kevkev
2,6413 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.
![]()
answered Dec 4, 2008 at 1:11
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
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 BellajBadr Bellaj
10.5k2 gold badges39 silver badges39 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
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.
answered Jan 7, 2009 at 14:22
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
liushuaikobeliushuaikobe
2,1221 gold badge23 silver badges26 bronze badges
1
- You must have the file __ init__.py in the same directory where it’s the file that you are importing.
- 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 GomesIasmini Gomes
6571 gold badge8 silver badges14 bronze badges
0
My two cents:

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.
answered Sep 6, 2014 at 11:17
Mr_and_Mrs_DMr_and_Mrs_D
31.1k37 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
![]()
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.

Enjoy.
answered Feb 18, 2019 at 3:35
![]()
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
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.
![]()
answered Sep 4, 2013 at 2:52
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
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-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
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
![]()
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
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
![]()
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
![]()
GhotiGhoti
7374 silver badges18 bronze badges
another cause makes this issue
file.py
#!/bin/python
from bs4 import BeautifulSoup
- if your default
pythonispyyhon2
$ file $(which python)
/sbin/python: symbolic link to python2
file.pyneedpython3, for this case(bs4)- you can not execute this module with
python2like 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
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
4,8413 gold badges34 silver badges36 bronze badges
answered Aug 8, 2014 at 8:36
![]()
SayseSayse
42.2k14 gold badges77 silver badges142 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
![]()
RocketqRocketq
5,00420 gold badges75 silver badges122 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énToivo Säwén
1,6632 gold badges14 silver badges32 bronze badges
I think I see the same thing.
Very easy to reproduce.
- Type the name of the just imported Class
- I hit tab.
- Some kind of white space shows up. (Tab completion fails)
- Hit enter once, hit enter twice, Boom!
***************************************************************************
IPython post-mortem report
{'commit_hash': '223e783c4',
'commit_source': 'installation',
'default_encoding': 'utf-8',
'ipython_path': '/Users/damian/Projects/hypermind/env/lib/python3.8/site-packages/IPython',
'ipython_version': '7.19.0',
'os_name': 'posix',
'platform': 'macOS-10.15.7-x86_64-i386-64bit',
'sys_executable': '/Users/damian/Projects/hypermind/env/bin/python',
'sys_platform': 'darwin',
'sys_version': '3.8.5 (default, Jul 21 2020, 10:48:26) n'
'[Clang 11.0.3 (clang-1103.0.32.62)]'}
***************************************************************************
***************************************************************************
Crash traceback:
---------------------------------------------------------------------------
---------------------------------------------------------------------------
TypeError Python 3.8.5: /Users/damian/Projects/hypermind/env/bin/python
Mon Dec 28 23:01:36 2020
A problem occurred executing Python code. Here is the sequence of function
calls leading up to the error, with the most recent (innermost) call last.
~/Projects/hypermind/env/lib/python3.8/site-packages/IPython/terminal/ptutils.py in get_completions(self=<IPython.terminal.ptutils.IPythonPTCompleter object>, document=Document('Edge', 4), complete_event=CompleteEvent(text_inserted=False, completion_requested=True))
112 try:
--> 113 yield from self._get_completions(body, offset, cursor_position, self.ipy_completer)
self._get_completions = <function IPythonPTCompleter._get_completions at 0x103d6d550>
body = 'Edge'
offset = 4
cursor_position = 4
self.ipy_completer = <IPython.core.completer.IPCompleter object at 0x103eaa790>
114 except Exception as e:
~/Projects/hypermind/env/lib/python3.8/site-packages/IPython/terminal/ptutils.py in _get_completions(body='Edge', offset=4, cursor_position=4, ipyc=<IPython.core.completer.IPCompleter object>)
128 body, ipyc.completions(body, offset))
--> 129 for c in completions:
c = undefined
completions = <generator object _deduplicate_completions at 0x1041fb900>
130 if not c.text:
~/Projects/hypermind/env/lib/python3.8/site-packages/IPython/core/completer.py in _deduplicate_completions(text='Edge', completions=<generator object IPCompleter.completions>)
437 """
--> 438 completions = list(completions)
completions = <generator object IPCompleter.completions at 0x1041fb890>
global list = undefined
439 if not completions:
~/Projects/hypermind/env/lib/python3.8/site-packages/IPython/core/completer.py in completions(self=<IPython.core.completer.IPCompleter object>, text='Edge', offset=4)
1817 try:
-> 1818 for c in self._completions(text, offset, _timeout=self.jedi_compute_type_timeout/1000):
c = undefined
self._completions = <bound method IPCompleter._completions of <IPython.core.completer.IPCompleter object at 0x103eaa790>>
text = 'Edge'
offset = 4
global _timeout = undefined
self.jedi_compute_type_timeout = 400
1819 if c and (c in seen):
~/Projects/hypermind/env/lib/python3.8/site-packages/IPython/core/completer.py in _completions(self=<IPython.core.completer.IPCompleter object>, full_text='Edge', offset=4, _timeout=0.4)
1860
-> 1861 matched_text, matches, matches_origin, jedi_matches = self._complete(
matched_text = undefined
matches = undefined
matches_origin = undefined
jedi_matches = undefined
self._complete = <bound method IPCompleter._complete of <IPython.core.completer.IPCompleter object at 0x103eaa790>>
full_text = 'Edge'
cursor_line = 0
global cursor_pos = undefined
cursor_column = 4
1862 full_text=full_text, cursor_line=cursor_line, cursor_pos=cursor_column)
~/Projects/hypermind/env/lib/python3.8/site-packages/IPython/core/completer.py in _complete(self=<IPython.core.completer.IPCompleter object>, cursor_line=0, cursor_pos=4, line_buffer='Edge', text='Edge', full_text='Edge')
2028 full_text = line_buffer
-> 2029 completions = self._jedi_matches(
completions = ()
self._jedi_matches = <bound method IPCompleter._jedi_matches of <IPython.core.completer.IPCompleter object at 0x103eaa790>>
cursor_pos = 4
cursor_line = 0
full_text = 'Edge'
2030 cursor_pos, cursor_line, full_text)
~/Projects/hypermind/env/lib/python3.8/site-packages/IPython/core/completer.py in _jedi_matches(self=<IPython.core.completer.IPCompleter object>, cursor_column=4, cursor_line=0, text='Edge')
1372
-> 1373 interpreter = jedi.Interpreter(
interpreter = undefined
global jedi.Interpreter = <class 'jedi.api.Interpreter'>
text = 'Edge'
offset = 4
namespaces = [{'__name__': '__main__', '__doc__': 'Automatically created module for IPython interactive environment', '__package__': None, '__loader__': None, '__spec__': None, '__builtin__': <module 'builtins' (built-in)>, '__builtins__': <module 'builtins' (built-in)>, '_ih': ['', "get_ipython().run_line_magic('config', 'Application.verbose_crash=True')", 'from hypergraph.models import Vertex, Edge'], '_oh': {}, '_dh': ['/Users/damian/Projects/hypermind/hypermind'], 'In': ['', "get_ipython().run_line_magic('config', 'Application.verbose_crash=True')", 'from hypergraph.models import Vertex, Edge'], 'Out': {}, 'get_ipython': <bound method InteractiveShell.get_ipython of <IPython.terminal.interactiveshell.TerminalInteractiveShell object at 0x103eaf280>>, 'exit': <IPython.core.autocall.ExitAutocall object at 0x103eaa7f0>, 'quit': <IPython.core.autocall.ExitAutocall object at 0x103eaa7f0>, '_': '', '__': '', '___': '', '_i': '%config Application.verbose_crash=True', '_ii': '', '_iii': '', '_i1': '%config Application.verbose_crash=True', '_i2': 'from hypergraph.models import Vertex, Edge', 'Vertex': <class 'hypergraph.models.Vertex'>, 'Edge': <class 'hypergraph.models.Edge'>}, {'__name__': '__main__', '__doc__': 'Automatically created module for IPython interactive environment', '__package__': None, '__loader__': None, '__spec__': None, '__builtin__': <module 'builtins' (built-in)>, '__builtins__': <module 'builtins' (built-in)>, '_ih': ['', "get_ipython().run_line_magic('config', 'Application.verbose_crash=True')", 'from hypergraph.models import Vertex, Edge'], '_oh': {}, '_dh': ['/Users/damian/Projects/hypermind/hypermind'], 'In': ['', "get_ipython().run_line_magic('config', 'Application.verbose_crash=True')", 'from hypergraph.models import Vertex, Edge'], 'Out': {}, 'get_ipython': <bound method InteractiveShell.get_ipython of <IPython.terminal.interactiveshell.TerminalInteractiveShell object at 0x103eaf280>>, 'exit': <IPython.core.autocall.ExitAutocall object at 0x103eaa7f0>, 'quit': <IPython.core.autocall.ExitAutocall object at 0x103eaa7f0>, '_': '', '__': '', '___': '', '_i': '%config Application.verbose_crash=True', '_ii': '', '_iii': '', '_i1': '%config Application.verbose_crash=True', '_i2': 'from hypergraph.models import Vertex, Edge', 'Vertex': <class 'hypergraph.models.Vertex'>, 'Edge': <class 'hypergraph.models.Edge'>}]
global column = undefined
cursor_column = 4
global line = undefined
cursor_line = 0
1374 text[:offset], namespaces, column=cursor_column, line=cursor_line + 1)
~/Projects/hypermind/env/lib/python3.8/site-packages/jedi/api/__init__.py in __init__(self=<class 'jedi.api.Interpreter'> instance, code='Edge', namespaces=[{'Edge': <class 'hypergraph.models.Edge'>, 'In': ['', "get_ipython().run_line_magic('config', 'Application.verbose_crash=True')", 'from hypergraph.models import Vertex, Edge'], 'Out': {}, 'Vertex': <class 'hypergraph.models.Vertex'>, '_': '', '__': '', '___': '', '__builtin__': <module 'builtins' (built-in)>, '__builtins__': <module 'builtins' (built-in)>, '__doc__': 'Automatically created module for IPython interactive environment', ...}, {'Edge': <class 'hypergraph.models.Edge'>, 'In': ['', "get_ipython().run_line_magic('config', 'Application.verbose_crash=True')", 'from hypergraph.models import Vertex, Edge'], 'Out': {}, 'Vertex': <class 'hypergraph.models.Vertex'>, '_': '', '__': '', '___': '', '__builtin__': <module 'builtins' (built-in)>, '__builtins__': <module 'builtins' (built-in)>, '__doc__': 'Automatically created module for IPython interactive environment', ...}], **kwds={'column': 4, 'line': 1})
724
--> 725 super().__init__(code, environment=environment,
global super.__init__ = undefined
code = 'Edge'
environment = <jedi.api.environment.InterpreterEnvironment object at 0x10413d7f0>
global project = <module 'jedi.api.project' from '/Users/damian/Projects/hypermind/env/lib/python3.8/site-packages/jedi/api/project.py'>
global Project = <class 'jedi.api.project.Project'>
global Path.cwd = <bound method Path.cwd of <class 'pathlib.Path'>>
kwds = {'column': 4, 'line': 1}
726 project=Project(Path.cwd()), **kwds)
TypeError: __init__() got an unexpected keyword argument 'column'
During handling of the above exception, another exception occurred:
---------------------------------------------------------------------------
NameError Python 3.8.5: /Users/damian/Projects/hypermind/env/bin/python
Mon Dec 28 23:01:36 2020
A problem occurred executing Python code. Here is the sequence of function
calls leading up to the error, with the most recent (innermost) call last.
~/Projects/hypermind/hypermind/manage.py in <module>
7 def main():
8 """Run administrative tasks."""
9 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hypermind.settings")
10 try:
11 from django.core.management import execute_from_command_line
12 except ImportError as exc:
13 raise ImportError(
14 "Couldn't import Django. Are you sure it's installed and "
15 "available on your PYTHONPATH environment variable? Did you "
16 "forget to activate a virtual environment?"
17 ) from exc
18 execute_from_command_line(sys.argv)
19
20
21 if __name__ == "__main__":
---> 22 main()
global main = <function main at 0x101b2a160>
~/Projects/hypermind/hypermind/manage.py in main()
3 import os
4 import sys
5
6
7 def main():
8 """Run administrative tasks."""
9 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hypermind.settings")
10 try:
11 from django.core.management import execute_from_command_line
12 except ImportError as exc:
13 raise ImportError(
14 "Couldn't import Django. Are you sure it's installed and "
15 "available on your PYTHONPATH environment variable? Did you "
16 "forget to activate a virtual environment?"
17 ) from exc
---> 18 execute_from_command_line(sys.argv)
execute_from_command_line = <function execute_from_command_line at 0x1024e28b0>
global sys.argv = ['manage.py', 'shell']
19
20
21 if __name__ == "__main__":
22 main()
~/Projects/hypermind/env/lib/python3.8/site-packages/django/core/management/__init__.py in execute_from_command_line(argv=['manage.py', 'shell'])
386 else:
387 self.fetch_command(options.args[0]).print_help(self.prog_name, options.args[0])
388 # Special-cases: We want 'django-admin --version' and
389 # 'django-admin --help' to work, for backwards compatibility.
390 elif subcommand == 'version' or self.argv[1:] == ['--version']:
391 sys.stdout.write(django.get_version() + 'n')
392 elif self.argv[1:] in (['--help'], ['-h']):
393 sys.stdout.write(self.main_help_text() + 'n')
394 else:
395 self.fetch_command(subcommand).run_from_argv(self.argv)
396
397
398 def execute_from_command_line(argv=None):
399 """Run a ManagementUtility."""
400 utility = ManagementUtility(argv)
--> 401 utility.execute()
utility.execute = <bound method ManagementUtility.execute of <django.core.management.ManagementUtility object at 0x101ab3a90>>
~/Projects/hypermind/env/lib/python3.8/site-packages/django/core/management/__init__.py in execute(self=<django.core.management.ManagementUtility object>)
380
381 if subcommand == 'help':
382 if '--commands' in args:
383 sys.stdout.write(self.main_help_text(commands_only=True) + 'n')
384 elif not options.args:
385 sys.stdout.write(self.main_help_text() + 'n')
386 else:
387 self.fetch_command(options.args[0]).print_help(self.prog_name, options.args[0])
388 # Special-cases: We want 'django-admin --version' and
389 # 'django-admin --help' to work, for backwards compatibility.
390 elif subcommand == 'version' or self.argv[1:] == ['--version']:
391 sys.stdout.write(django.get_version() + 'n')
392 elif self.argv[1:] in (['--help'], ['-h']):
393 sys.stdout.write(self.main_help_text() + 'n')
394 else:
--> 395 self.fetch_command(subcommand).run_from_argv(self.argv)
self.fetch_command = <bound method ManagementUtility.fetch_command of <django.core.management.ManagementUtility object at 0x101ab3a90>>
subcommand.run_from_argv = undefined
self.argv = ['manage.py', 'shell']
396
397
398 def execute_from_command_line(argv=None):
399 """Run a ManagementUtility."""
400 utility = ManagementUtility(argv)
401 utility.execute()
~/Projects/hypermind/env/lib/python3.8/site-packages/django/core/management/base.py in run_from_argv(self=<django.core.management.commands.shell.Command object>, argv=['manage.py', 'shell'])
315 Set up any environment changes requested (e.g., Python path
316 and Django settings), then run this command. If the
317 command raises a ``CommandError``, intercept it and print it sensibly
318 to stderr. If the ``--traceback`` option is present or the raised
319 ``Exception`` is not ``CommandError``, raise it.
320 """
321 self._called_from_command_line = True
322 parser = self.create_parser(argv[0], argv[1])
323
324 options = parser.parse_args(argv[2:])
325 cmd_options = vars(options)
326 # Move positional args out of options to mimic legacy optparse
327 args = cmd_options.pop('args', ())
328 handle_default_options(options)
329 try:
--> 330 self.execute(*args, **cmd_options)
self.execute = <bound method BaseCommand.execute of <django.core.management.commands.shell.Command object at 0x102b766d0>>
args = ()
cmd_options = {'verbosity': 1, 'settings': None, 'pythonpath': None, 'traceback': False, 'no_color': False, 'force_color': False, 'no_startup': False, 'interface': None, 'command': None}
331 except CommandError as e:
332 if options.traceback:
333 raise
334
335 # SystemCheckError takes care of its own formatting.
336 if isinstance(e, SystemCheckError):
337 self.stderr.write(str(e), lambda x: x)
338 else:
339 self.stderr.write('%s: %s' % (e.__class__.__name__, e))
340 sys.exit(e.returncode)
341 finally:
342 try:
343 connections.close_all()
344 except ImproperlyConfigured:
345 # Ignore if connections aren't setup at this point (e.g. no
~/Projects/hypermind/env/lib/python3.8/site-packages/django/core/management/base.py in execute(self=<django.core.management.commands.shell.Command object>, *args=(), **options={'command': None, 'force_color': False, 'interface': None, 'no_color': False, 'no_startup': False, 'pythonpath': None, 'settings': None, 'traceback': False, 'verbosity': 1})
356 raise CommandError("The --no-color and --force-color options can't be used together.")
357 if options['force_color']:
358 self.style = color_style(force_color=True)
359 elif options['no_color']:
360 self.style = no_style()
361 self.stderr.style_func = None
362 if options.get('stdout'):
363 self.stdout = OutputWrapper(options['stdout'])
364 if options.get('stderr'):
365 self.stderr = OutputWrapper(options['stderr'])
366
367 if self.requires_system_checks and not options['skip_checks']:
368 self.check()
369 if self.requires_migrations_checks:
370 self.check_migrations()
--> 371 output = self.handle(*args, **options)
output = undefined
self.handle = <bound method Command.handle of <django.core.management.commands.shell.Command object at 0x102b766d0>>
args = ()
options = {'verbosity': 1, 'settings': None, 'pythonpath': None, 'traceback': False, 'no_color': False, 'force_color': False, 'no_startup': False, 'interface': None, 'command': None}
372 if output:
373 if self.output_transaction:
374 connection = connections[options.get('database', DEFAULT_DB_ALIAS)]
375 output = '%sn%sn%s' % (
376 self.style.SQL_KEYWORD(connection.ops.start_transaction_sql()),
377 output,
378 self.style.SQL_KEYWORD(connection.ops.end_transaction_sql()),
379 )
380 self.stdout.write(output)
381 return output
382
383 def check(self, app_configs=None, tags=None, display_num_errors=False,
384 include_deployment_checks=False, fail_level=checks.ERROR,
385 databases=None):
386 """
~/Projects/hypermind/env/lib/python3.8/site-packages/django/core/management/commands/shell.py in handle(self=<django.core.management.commands.shell.Command object>, **options={'command': None, 'force_color': False, 'interface': None, 'no_color': False, 'no_startup': False, 'pythonpath': None, 'settings': None, 'traceback': False, 'verbosity': 1})
85 # Execute the command and exit.
86 if options['command']:
87 exec(options['command'])
88 return
89
90 # Execute stdin if it has anything to read and exit.
91 # Not supported on Windows due to select.select() limitations.
92 if sys.platform != 'win32' and not sys.stdin.isatty() and select.select([sys.stdin], [], [], 0)[0]:
93 exec(sys.stdin.read())
94 return
95
96 available_shells = [options['interface']] if options['interface'] else self.shells
97
98 for shell in available_shells:
99 try:
--> 100 return getattr(self, shell)(options)
global getattr = undefined
self = <django.core.management.commands.shell.Command object at 0x102b766d0>
shell = 'ipython'
options = {'verbosity': 1, 'settings': None, 'pythonpath': None, 'traceback': False, 'no_color': False, 'force_color': False, 'no_startup': False, 'interface': None, 'command': None}
101 except ImportError:
102 pass
103 raise CommandError("Couldn't import {} interface.".format(shell))
~/Projects/hypermind/env/lib/python3.8/site-packages/django/core/management/commands/shell.py in ipython(self=<django.core.management.commands.shell.Command object>, options={'command': None, 'force_color': False, 'interface': None, 'no_color': False, 'no_startup': False, 'pythonpath': None, 'settings': None, 'traceback': False, 'verbosity': 1})
21 parser.add_argument(
22 '--no-startup', action='store_true',
23 help='When using plain Python, ignore the PYTHONSTARTUP environment variable and ~/.pythonrc.py script.',
24 )
25 parser.add_argument(
26 '-i', '--interface', choices=self.shells,
27 help='Specify an interactive interpreter interface. Available options: "ipython", "bpython", and "python"',
28 )
29 parser.add_argument(
30 '-c', '--command',
31 help='Instead of opening an interactive shell, run a command as Django and exit.',
32 )
33
34 def ipython(self, options):
35 from IPython import start_ipython
---> 36 start_ipython(argv=[])
start_ipython = <function start_ipython at 0x103e88280>
global argv = undefined
37
38 def bpython(self, options):
39 import bpython
40 bpython.embed()
41
42 def python(self, options):
43 import code
44
45 # Set up a dictionary to serve as the environment for the shell, so
46 # that tab completion works on objects that are imported at runtime.
47 imported_objects = {}
48 try: # Try activating rlcompleter, because it's handy.
49 import readline
50 except ImportError:
51 pass
~/Projects/hypermind/env/lib/python3.8/site-packages/IPython/__init__.py in start_ipython(argv=[], **kwargs={})
111 This is a public API method, and will survive implementation changes.
112
113 Parameters
114 ----------
115
116 argv : list or None, optional
117 If unspecified or None, IPython will parse command-line options from sys.argv.
118 To prevent any command-line parsing, pass an empty list: `argv=[]`.
119 user_ns : dict, optional
120 specify this dictionary to initialize the IPython user namespace with particular values.
121 kwargs : various, optional
122 Any other kwargs will be passed to the Application constructor,
123 such as `config`.
124 """
125 from IPython.terminal.ipapp import launch_new_instance
--> 126 return launch_new_instance(argv=argv, **kwargs)
launch_new_instance = <bound method Application.launch_instance of <class 'IPython.terminal.ipapp.TerminalIPythonApp'>>
argv = []
kwargs = {}
127
128 def start_kernel(argv=None, **kwargs):
129 """Launch a normal IPython kernel instance (as opposed to embedded)
130
131 `IPython.embed_kernel()` puts a shell in a particular calling scope,
132 such as a function or method for debugging purposes,
133 which is often not desirable.
134
135 `start_kernel()` does full, regular IPython initialization,
136 including loading startup files, configuration, etc.
137 much of which is skipped by `embed()`.
138
139 Parameters
140 ----------
141
~/Projects/hypermind/env/lib/python3.8/site-packages/traitlets/config/application.py in launch_instance(cls=<class 'IPython.terminal.ipapp.TerminalIPythonApp'>, argv=[], **kwargs={})
830 lines.append(cls.class_config_section(config_classes))
831 return 'n'.join(lines)
832
833 def exit(self, exit_status=0):
834 self.log.debug("Exiting application: %s" % self.name)
835 sys.exit(exit_status)
836
837 @classmethod
838 def launch_instance(cls, argv=None, **kwargs):
839 """Launch a global instance of this Application
840
841 If a global instance already exists, this reinitializes and starts it
842 """
843 app = cls.instance(**kwargs)
844 app.initialize(argv)
--> 845 app.start()
app.start = <bound method TerminalIPythonApp.start of <IPython.terminal.ipapp.TerminalIPythonApp object at 0x103378d00>>
846
847 #-----------------------------------------------------------------------------
848 # utility functions, for convenience
849 #-----------------------------------------------------------------------------
850
851 default_aliases = Application.aliases
852 default_flags = Application.flags
853
854 def boolean_flag(name, configurable, set_help='', unset_help=''):
855 """Helper for building basic --trait, --no-trait flags.
856
857 Parameters
858 ----------
859 name : str
860 The name of the flag.
~/Projects/hypermind/env/lib/python3.8/site-packages/IPython/terminal/ipapp.py in start(self=<IPython.terminal.ipapp.TerminalIPythonApp object>)
341 if self.log_level <= logging.INFO: print()
342
343 def _pylab_changed(self, name, old, new):
344 """Replace --pylab='inline' with --pylab='auto'"""
345 if new == 'inline':
346 warnings.warn("'inline' not available as pylab backend, "
347 "using 'auto' instead.")
348 self.pylab = 'auto'
349
350 def start(self):
351 if self.subapp is not None:
352 return self.subapp.start()
353 # perform any prexec steps:
354 if self.interact:
355 self.log.debug("Starting IPython's mainloop...")
--> 356 self.shell.mainloop()
self.shell.mainloop = <bound method TerminalInteractiveShell.mainloop of <IPython.terminal.interactiveshell.TerminalInteractiveShell object at 0x103eaf280>>
357 else:
358 self.log.debug("IPython not interactive...")
359 if not self.shell.last_execution_succeeded:
360 sys.exit(1)
361
362 def load_default_config(ipython_dir=None):
363 """Load the default config file from the default ipython_dir.
364
365 This is useful for embedded shells.
366 """
367 if ipython_dir is None:
368 ipython_dir = get_ipython_dir()
369
370 profile_dir = os.path.join(ipython_dir, 'profile_default')
371 app = TerminalIPythonApp()
~/Projects/hypermind/env/lib/python3.8/site-packages/IPython/terminal/interactiveshell.py in mainloop(self=<IPython.terminal.interactiveshell.TerminalInteractiveShell object>, display_banner=<object object>)
549 if (not self.confirm_exit)
550 or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
551 self.ask_exit()
552
553 else:
554 if code:
555 self.run_cell(code, store_history=True)
556
557 def mainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED):
558 # An extra layer of protection in case someone mashing Ctrl-C breaks
559 # out of our internal code.
560 if display_banner is not DISPLAY_BANNER_DEPRECATED:
561 warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
562 while True:
563 try:
--> 564 self.interact()
self.interact = <bound method TerminalInteractiveShell.interact of <IPython.terminal.interactiveshell.TerminalInteractiveShell object at 0x103eaf280>>
565 break
566 except KeyboardInterrupt as e:
567 print("n%s escaped interact()n" % type(e).__name__)
568 finally:
569 # An interrupt during the eventloop will mess up the
570 # internal state of the prompt_toolkit library.
571 # Stopping the eventloop fixes this, see
572 # https://github.com/ipython/ipython/pull/9867
573 if hasattr(self, '_eventloop'):
574 self._eventloop.stop()
575
576 self.restore_term_title()
577
578
579 _inputhook = None
~/Projects/hypermind/env/lib/python3.8/site-packages/IPython/terminal/interactiveshell.py in interact(self=<IPython.terminal.interactiveshell.TerminalInteractiveShell object>, display_banner=<object object>)
532 def ask_exit(self):
533 self.keep_running = False
534
535 rl_next_input = None
536
537 def interact(self, display_banner=DISPLAY_BANNER_DEPRECATED):
538
539 if display_banner is not DISPLAY_BANNER_DEPRECATED:
540 warn('interact `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
541
542 self.keep_running = True
543 while self.keep_running:
544 print(self.separate_in, end='')
545
546 try:
--> 547 code = self.prompt_for_code()
code = 'from hypergraph.models import Vertex, Edge'
self.prompt_for_code = <bound method TerminalInteractiveShell.prompt_for_code of <IPython.terminal.interactiveshell.TerminalInteractiveShell object at 0x103eaf280>>
548 except EOFError:
549 if (not self.confirm_exit)
550 or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
551 self.ask_exit()
552
553 else:
554 if code:
555 self.run_cell(code, store_history=True)
556
557 def mainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED):
558 # An extra layer of protection in case someone mashing Ctrl-C breaks
559 # out of our internal code.
560 if display_banner is not DISPLAY_BANNER_DEPRECATED:
561 warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
562 while True:
~/Projects/hypermind/env/lib/python3.8/site-packages/IPython/terminal/interactiveshell.py in prompt_for_code(self=<IPython.terminal.interactiveshell.TerminalInteractiveShell object>)
458 # In order to make sure that asyncio code written in the
459 # interactive shell doesn't interfere with the prompt, we run the
460 # prompt in a different event loop.
461 # If we don't do this, people could spawn coroutine with a
462 # while/true inside which will freeze the prompt.
463
464 try:
465 old_loop = asyncio.get_event_loop()
466 except RuntimeError:
467 # This happens when the user used `asyncio.run()`.
468 old_loop = None
469
470 asyncio.set_event_loop(self.pt_loop)
471 try:
472 with patch_stdout(raw=True):
--> 473 text = self.pt_app.prompt(
text = undefined
self.pt_app.prompt = <bound method PromptSession.prompt of <prompt_toolkit.shortcuts.prompt.PromptSession object at 0x104036790>>
default = ''
self._extra_prompt_options = <bound method TerminalInteractiveShell._extra_prompt_options of <IPython.terminal.interactiveshell.TerminalInteractiveShell object at 0x103eaf280>>
474 default=default,
475 **self._extra_prompt_options())
476 finally:
477 # Restore the original event loop.
478 asyncio.set_event_loop(old_loop)
479
480 return text
481
482 def enable_win_unicode_console(self):
483 # Since IPython 7.10 doesn't support python < 3.6 and PEP 528, Python uses the unicode APIs for the Windows
484 # console by default, so WUC shouldn't be needed.
485 from warnings import warn
486 warn("`enable_win_unicode_console` is deprecated since IPython 7.10, does not do anything and will be removed in the future",
487 DeprecationWarning,
488 stacklevel=2)
~/Projects/hypermind/env/lib/python3.8/site-packages/prompt_toolkit/shortcuts/prompt.py in prompt(self=<prompt_toolkit.shortcuts.prompt.PromptSession object>, message=<prompt_toolkit.formatted_text.pygments.PygmentsTokens object>, editing_mode=None, refresh_interval=None, vi_mode=None, lexer=<IPython.terminal.ptutils.IPythonPTLexer object>, completer=None, complete_in_thread=False, is_password=None, key_bindings=None, bottom_toolbar=None, style=None, color_depth=None, include_default_pygments_style=None, style_transformation=None, swap_light_and_dark_colors=None, rprompt=None, multiline=True, prompt_continuation=<function TerminalInteractiveShell._extra_prompt_options.<locals>.<lambda>>, wrap_lines=None, enable_history_search=None, search_ignore_case=None, complete_while_typing=None, validate_while_typing=None, complete_style=<CompleteStyle.MULTI_COLUMN: 'MULTI_COLUMN'>, auto_suggest=None, validator=None, clipboard=None, mouse_support=None, input_processors=[ConditionalProcessor(processor=<prompt_toolkit.l...rompt_options.<locals>.<lambda> at 0x104107790>))], placeholder=None, reserve_space_for_menu=6, enable_system_prompt=None, enable_suspend=None, enable_open_in_editor=None, tempfile_suffix=None, tempfile=None, default='', accept_default=False, pre_run=None, set_exception_handler=True)
998 self.tempfile_suffix = tempfile_suffix
999 if tempfile is not None:
1000 self.tempfile = tempfile
1001
1002 self._add_pre_run_callables(pre_run, accept_default)
1003 self.default_buffer.reset(
1004 default if isinstance(default, Document) else Document(default)
1005 )
1006 self.app.refresh_interval = self.refresh_interval # This is not reactive.
1007
1008 # If we are using the default output, and have a dumb terminal. Use the
1009 # dumb prompt.
1010 if self._output is None and is_dumb_terminal():
1011 return get_event_loop().run_until_complete(self._dumb_prompt(self.message))
1012
-> 1013 return self.app.run(set_exception_handler=set_exception_handler)
self.app.run = <bound method Application.run of <prompt_toolkit.application.application.Application object at 0x104053580>>
set_exception_handler = True
1014
1015 async def _dumb_prompt(self, message: AnyFormattedText = "") -> _T:
1016 """
1017 Prompt function for dumb terminals.
1018
1019 Dumb terminals have minimum rendering capabilities. We can only print
1020 text to the screen. We can't use colors, and we can't do cursor
1021 movements. The Emacs inferior shell is an example of a dumb terminal.
1022
1023 We will show the prompt, and wait for the input. We still handle arrow
1024 keys, and all custom key bindings, but we don't really render the
1025 cursor movements. Instead we only print the typed character that's
1026 right before the cursor.
1027 """
1028 # Send prompt to output.
~/Projects/hypermind/env/lib/python3.8/site-packages/prompt_toolkit/application/application.py in run(self=<prompt_toolkit.application.application.Application object>, pre_run=None, set_exception_handler=True)
801 """
802 # We don't create a new event loop by default, because we want to be
803 # sure that when this is called multiple times, each call of `run()`
804 # goes through the same event loop. This way, users can schedule
805 # background-tasks that keep running across multiple prompts.
806 try:
807 loop = get_event_loop()
808 except RuntimeError:
809 # Possibly we are not running in the main thread, where no event
810 # loop is set by default. Or somebody called `asyncio.run()`
811 # before, which closes the existing event loop. We can create a new
812 # loop.
813 loop = new_event_loop()
814 set_event_loop(loop)
815
--> 816 return loop.run_until_complete(
loop.run_until_complete = <bound method BaseEventLoop.run_until_complete of <_UnixSelectorEventLoop running=False closed=False debug=False>>
self.run_async = <bound method Application.run_async of <prompt_toolkit.application.application.Application object at 0x104053580>>
pre_run = None
set_exception_handler = True
817 self.run_async(pre_run=pre_run, set_exception_handler=set_exception_handler)
818 )
819
820 def _handle_exception(
821 self, loop: AbstractEventLoop, context: Dict[str, Any]
822 ) -> None:
823 """
824 Handler for event loop exceptions.
825 This will print the exception, using run_in_terminal.
826 """
827 # For Python 2: we have to get traceback at this point, because
828 # we're still in the 'except:' block of the event loop where the
829 # traceback is still available. Moving this code in the
830 # 'print_exception' coroutine will loose the exception.
831 tb = get_traceback_from_context(context)
/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/base_events.py in run_until_complete(self=<_UnixSelectorEventLoop running=False closed=False debug=False>, future=<Task finished name='Task-32' coro=<Application....exception=NameError("name 'sys' is not defined")>)
601 future.add_done_callback(_run_until_complete_cb)
602 try:
603 self.run_forever()
604 except:
605 if new_task and future.done() and not future.cancelled():
606 # The coroutine raised a BaseException. Consume the exception
607 # to not log a warning, the caller doesn't have access to the
608 # local task.
609 future.exception()
610 raise
611 finally:
612 future.remove_done_callback(_run_until_complete_cb)
613 if not future.done():
614 raise RuntimeError('Event loop stopped before Future completed.')
615
--> 616 return future.result()
future.result = <built-in method result of _asyncio.Task object at 0x10401f5e0>
617
618 def stop(self):
619 """Stop running the event loop.
620
621 Every callback already scheduled will still run. This simply informs
622 run_forever to stop looping after a complete iteration.
623 """
624 self._stopping = True
625
626 def close(self):
627 """Close the event loop.
628
629 This clears the queues and shuts down the executor,
630 but does not wait for the executor to finish.
631
~/Projects/hypermind/env/lib/python3.8/site-packages/prompt_toolkit/application/application.py in run_async(self=<prompt_toolkit.application.application.Application object>, pre_run=None, set_exception_handler=True)
768 # go in the finally! If `_run_async` raises
769 # `KeyboardInterrupt`, we still want to wait for the
770 # background tasks.
771 await self.cancel_and_wait_for_background_tasks()
772
773 # Set the `_is_running` flag to `False`. Normally this
774 # happened already in the finally block in `run_async`
775 # above, but in case of exceptions, that's not always the
776 # case.
777 self._is_running = False
778 return result
779 finally:
780 if set_exception_handler:
781 loop.set_exception_handler(previous_exc_handler)
782
--> 783 return await _run_async2()
_run_async2 = <function Application.run_async.<locals>._run_async2 at 0x10401cb80>
784
785 def run(
786 self,
787 pre_run: Optional[Callable[[], None]] = None,
788 set_exception_handler: bool = True,
789 ) -> _AppResult:
790 """
791 A blocking 'run' call that waits until the UI is finished.
792
793 This will start the current asyncio event loop. If no loop is set for
794 the current thread, then it will create a new loop.
795
796 :param pre_run: Optional callable, which is called right after the
797 "reset" of the application.
798 :param set_exception_handler: When set, in case of an exception, go out
~/Projects/hypermind/env/lib/python3.8/site-packages/prompt_toolkit/application/application.py in _run_async2()
756
757 loop = get_event_loop()
758 if set_exception_handler:
759 previous_exc_handler = loop.get_exception_handler()
760 loop.set_exception_handler(self._handle_exception)
761
762 try:
763 with set_app(self):
764 try:
765 result = await _run_async()
766 finally:
767 # Wait for the background tasks to be done. This needs to
768 # go in the finally! If `_run_async` raises
769 # `KeyboardInterrupt`, we still want to wait for the
770 # background tasks.
--> 771 await self.cancel_and_wait_for_background_tasks()
global self.cancel_and_wait_for_background_tasks = undefined
772
773 # Set the `_is_running` flag to `False`. Normally this
774 # happened already in the finally block in `run_async`
775 # above, but in case of exceptions, that's not always the
776 # case.
777 self._is_running = False
778 return result
779 finally:
780 if set_exception_handler:
781 loop.set_exception_handler(previous_exc_handler)
782
783 return await _run_async2()
784
785 def run(
786 self,
~/Projects/hypermind/env/lib/python3.8/site-packages/prompt_toolkit/application/application.py in cancel_and_wait_for_background_tasks(self=<prompt_toolkit.application.application.Application object>)
857
858 async def cancel_and_wait_for_background_tasks(self) -> None:
859 """
860 Cancel all background tasks, and wait for the cancellation to be done.
861 If any of the background tasks raised an exception, this will also
862 propagate the exception.
863
864 (If we had nurseries like Trio, this would be the `__aexit__` of a
865 nursery.)
866 """
867 for task in self.background_tasks:
868 task.cancel()
869
870 for task in self.background_tasks:
871 try:
--> 872 await task
task = <Task finished name='Task-53' coro=<Buffer._create_completer_coroutine.<locals>.async_completer() done, defined at /Users/damian/Projects/hypermind/env/lib/python3.8/site-packages/prompt_toolkit/buffer.py:1841> exception=NameError("name 'sys' is not defined")>
873 except CancelledError:
874 pass
875
876 def cpr_not_supported_callback(self) -> None:
877 """
878 Called when we don't receive the cursor position response in time.
879 """
880 if not self.output.responds_to_cpr:
881 return # We know about this already.
882
883 def in_terminal() -> None:
884 self.output.write(
885 "WARNING: your terminal doesn't support cursor position requests (CPR).rn"
886 )
887 self.output.flush()
~/Projects/hypermind/env/lib/python3.8/site-packages/prompt_toolkit/buffer.py in new_coroutine(*a=(), **kw={'complete_event': CompleteEvent(text_inserted=False, completion_requested=True), 'insert_common_part': True, 'select_first': False, 'select_last': False})
1839 running = False
1840
1841 @wraps(coroutine)
1842 async def new_coroutine(*a: Any, **kw: Any) -> Any:
1843 nonlocal running
1844
1845 # Don't start a new function, if the previous is still in progress.
1846 if running:
1847 return
1848
1849 running = True
1850
1851 try:
1852 while True:
1853 try:
-> 1854 await coroutine(*a, **kw)
global coroutine = undefined
a = ()
kw = {'select_first': False, 'select_last': False, 'insert_common_part': True, 'complete_event': CompleteEvent(text_inserted=False, completion_requested=True)}
1855 except _Retry:
1856 continue
1857 else:
1858 return None
1859 finally:
1860 running = False
1861
1862 return cast(_T, new_coroutine)
1863
1864
1865 class _Retry(Exception):
1866 " Retry in `_only_one_at_a_time`. "
1867
1868
1869 def indent(buffer: Buffer, from_row: int, to_row: int, count: int = 1) -> None:
~/Projects/hypermind/env/lib/python3.8/site-packages/prompt_toolkit/buffer.py in async_completer(select_first=False, select_last=False, insert_common_part=True, complete_event=CompleteEvent(text_inserted=False, completion_requested=True))
1668 complete_event = complete_event or CompleteEvent(text_inserted=True)
1669
1670 # Don't complete when we already have completions.
1671 if self.complete_state or not self.completer:
1672 return
1673
1674 # Create an empty CompletionState.
1675 complete_state = CompletionState(original_document=self.document)
1676 self.complete_state = complete_state
1677
1678 def proceed() -> bool:
1679 """Keep retrieving completions. Input text has not yet changed
1680 while generating completions."""
1681 return self.complete_state == complete_state
1682
-> 1683 async for completion in self.completer.get_completions_async(
completion = undefined
global self.completer.get_completions_async = undefined
document = Document('Edge', 4)
complete_event = CompleteEvent(text_inserted=False, completion_requested=True)
1684 document, complete_event
1685 ):
1686 complete_state.completions.append(completion)
1687 self.on_completions_changed.fire()
1688
1689 # If the input text changes, abort.
1690 if not proceed():
1691 break
1692
1693 completions = complete_state.completions
1694
1695 # When there is only one completion, which has nothing to add, ignore it.
1696 if len(completions) == 1 and completion_does_nothing(
1697 document, completions[0]
1698 ):
~/Projects/hypermind/env/lib/python3.8/site-packages/prompt_toolkit/completion/base.py in get_completions_async(self=DynamicCompleter(<function PromptSession._create...tutils.IPythonPTCompleter object at 0x103edd5e0>), document=Document('Edge', 4), complete_event=CompleteEvent(text_inserted=False, completion_requested=True))
254
255 def __init__(self, get_completer: Callable[[], Optional[Completer]]) -> None:
256 self.get_completer = get_completer
257
258 def get_completions(
259 self, document: Document, complete_event: CompleteEvent
260 ) -> Iterable[Completion]:
261 completer = self.get_completer() or DummyCompleter()
262 return completer.get_completions(document, complete_event)
263
264 async def get_completions_async(
265 self, document: Document, complete_event: CompleteEvent
266 ) -> AsyncGenerator[Completion, None]:
267 completer = self.get_completer() or DummyCompleter()
268
--> 269 async for completion in completer.get_completions_async(
completion = undefined
completer.get_completions_async = <bound method Completer.get_completions_async of <IPython.terminal.ptutils.IPythonPTCompleter object at 0x103edd5e0>>
document = Document('Edge', 4)
complete_event = CompleteEvent(text_inserted=False, completion_requested=True)
270 document, complete_event
271 ):
272 yield completion
273
274 def __repr__(self) -> str:
275 return "DynamicCompleter(%r -> %r)" % (self.get_completer, self.get_completer())
276
277
278 class _MergedCompleter(Completer):
279 """
280 Combine several completers into one.
281 """
282
283 def __init__(self, completers: Sequence[Completer]) -> None:
284 self.completers = completers
~/Projects/hypermind/env/lib/python3.8/site-packages/prompt_toolkit/completion/base.py in get_completions_async(self=<IPython.terminal.ptutils.IPythonPTCompleter object>, document=Document('Edge', 4), complete_event=CompleteEvent(text_inserted=False, completion_requested=True))
181 :param document: :class:`~prompt_toolkit.document.Document` instance.
182 :param complete_event: :class:`.CompleteEvent` instance.
183 """
184 while False:
185 yield
186
187 async def get_completions_async(
188 self, document: Document, complete_event: CompleteEvent
189 ) -> AsyncGenerator[Completion, None]:
190 """
191 Asynchronous generator for completions. (Probably, you won't have to
192 override this.)
193
194 Asynchronous generator of :class:`.Completion` objects.
195 """
--> 196 for item in self.get_completions(document, complete_event):
item = undefined
self.get_completions = <bound method IPythonPTCompleter.get_completions of <IPython.terminal.ptutils.IPythonPTCompleter object at 0x103edd5e0>>
document = Document('Edge', 4)
complete_event = CompleteEvent(text_inserted=False, completion_requested=True)
197 yield item
198
199
200 class ThreadedCompleter(Completer):
201 """
202 Wrapper that runs the `get_completions` generator in a thread.
203
204 (Use this to prevent the user interface from becoming unresponsive if the
205 generation of completions takes too much time.)
206
207 The completions will be displayed as soon as they are produced. The user
208 can already select a completion, even if not all completions are displayed.
209 """
210
211 def __init__(self, completer: Completer) -> None:
~/Projects/hypermind/env/lib/python3.8/site-packages/IPython/terminal/ptutils.py in get_completions(self=<IPython.terminal.ptutils.IPythonPTCompleter object>, document=Document('Edge', 4), complete_event=CompleteEvent(text_inserted=False, completion_requested=True))
101 return
102 # Some bits of our completion system may print stuff (e.g. if a module
103 # is imported). This context manager ensures that doesn't interfere with
104 # the prompt.
105
106 with patch_stdout(), provisionalcompleter():
107 body = document.text
108 cursor_row = document.cursor_position_row
109 cursor_col = document.cursor_position_col
110 cursor_position = document.cursor_position
111 offset = cursor_to_position(body, cursor_row, cursor_col)
112 try:
113 yield from self._get_completions(body, offset, cursor_position, self.ipy_completer)
114 except Exception as e:
115 try:
--> 116 exc_type, exc_value, exc_tb = sys.exc_info()
exc_type = undefined
exc_value = undefined
exc_tb = undefined
global sys.exc_info = undefined
117 traceback.print_exception(exc_type, exc_value, exc_tb)
118 except AttributeError:
119 print('Unrecoverable Error in completions')
120
121 @staticmethod
122 def _get_completions(body, offset, cursor_position, ipyc):
123 """
124 Private equivalent of get_completions() use only for unit_testing.
125 """
126 debug = getattr(ipyc, 'debug', False)
127 completions = _deduplicate_completions(
128 body, ipyc.completions(body, offset))
129 for c in completions:
130 if not c.text:
131 # Guard against completion machinery giving us an empty string.
NameError: name 'sys' is not defined
***************************************************************************
History of session input:get_ipython().run_line_magic('config', 'Application.verbose_crash=True')from hypergraph.models import Vertex, Edge
*** Last line of input (may not be in above history):
from hypergraph.models import Vertex, Edge
