You might encounter a problem when installing a Python package in the project settings or in the Python Package tool window. Eventually, most of the issues are out of IDE control as PyCharm uses the pip package manager to perform the actual installation.
This article provides troubleshooting tips and covers some typical cases.
Install a package using the Terminal
The most viable troubleshooting action is to try installing the problematic package on the selected Python interpreter using the terminal. If you get an identical error message, then the problem is not in the IDE and you should review the rationales and typical cases, or search for a solution on the Internet.
Install a package on a virtual environment
-
Press Ctrl+Alt+S to open the IDE settings and select .
-
Expand the list of the available interpreters and click Show All.

-
Locate the target interpreter and press
.

Copy or memorize the path of the virtual environment and close the dialogs.
-
Open the terminal and run the following commands:
source <venv path>/bin/activate
pip install <package name>
-
Inspect and parse the results.
Install a package on a Conda environment
-
Open the terminal and run the following commands:
Conda < 4.6
Conda >= 4.6
activate <conda env name>
conda install <package name>conda activate <conda env name>
conda install <package name>Conda < 4.6
Conda >= 4.6
source activate <conda env name>
conda install <package name>conda activate <conda env name>
conda install <package name>See Conda documentation for more information on how to activate an environment.

One of the possible failure cases occurs when the target package is not available in the repositories supported by the Conda package manager.

-
Inspect and parse the results.
Install a package on a system interpreter
-
To check the path of the currently selected system interpreter that you were trying to install a package on, press Ctrl+Alt+S and go to .
-
Expand the list of the project interpreters and scroll it down, then select the item.

-
Locate the interpreter and press
.

Copy or memorize the path of the environment and close the dialogs.
-
Open the terminal and run the following commands:
cd <interpreter path>
-m pip install <package name>
You might need the admin privileges to install packages on a system interpreter.
-
Inspect and parse the results.
Parse the results
|
Result |
Action |
|---|---|
|
The package cannot be installed because the Python version doesn’t satisfy the package requirement. |
Try to create another Python interpreter that is based on the Python version that meets the requirement. |
|
The package cannot be installed because you don’t have permissions to install it. |
Try to install the package using super-user privileges, for example, |
|
The package cannot be installed because the package is not available in the repository that is supported by the selected package manager. Example: you’re trying to install a package that is not available in the Conda package manager repositories. |
Try to configure another type of Python interpreter for your project and install the package on it. See how to add and modify a Python interpreter in Configure a Python interpreter. |
|
The package cannot be installed and it matches one of the typical package installation failure cases. |
Check the cases and apply related workarounds. |
|
The package is successfully installed. |
File an issue in the PyCharm issue tracker and provide explicit details about the case including all console output, error messages, and screenshots indicating that you tried to install the package on the same interpreter in the terminal and in the project settings or in the Python Packages tool window. |
Review typical cases
Last modified: 16 December 2022
Сделал это, запустил через терминал. Вот код
| Python | ||
|
Выводит следующее:
Код
import face-recognition
File "<stdin>", line 1
import face-recognition
^
SyntaxError: invalid syntax
>>> import cv2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'cv2'
>>> import numpy as np
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'numpy'
>>> import os
>>> from datetime import datetime
>>>
>>> path = 'KnownFaces'
>>> images = []
>>> classNames = []
>>> myList = os.listdir(path)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [WinError 3] Системе не удается найти указанный путь: 'KnownFaces'
>>> print(myList)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'myList' is not defined
>>>
>>> for cls in myList:
... curImg = cv2.imread(f'{path}/{cls}')
... images.append(curImg)
... classNames.append(os.path.splitext(cls)[0])
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'myList' is not defined
>>> print(classNames)
[]
>>>
>>> def findEncodings(images):
... encodeList = []
... for img in images:
... img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
... encode = face_recognition.face_encodings(img)[0]
... encodeList.append(encode)
... return encodeList
...
>>> def markAttendance(name):
... with open("Attendance.csv", "r+") as f:
... myDataList = f.readlines()
... nameList = []
... for line in myDataList:
... entry = line.split(',')
... nameList.append(entry[0])
... if name not in nameList:
... now = datetime.now()
... dtString = now.strftime("%H:%M:%S")
... f.writelines(f'n{name}, {dtString}')
...
>>> encodeListKnown = findEncodings(images)
>>> print("Декодирование закончено")
Декодирование закончено
>>>
>>> cap = cv2.VideoCapture(0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'cv2' is not defined
>>>
>>> while True:
... success, img = cap.read()
... imgS = cv2.resize(img, (0, 0), None, 0.25, 0.25)
... imgS = cv2.cvtColor(imgS, cv2.COLOR_BGR2RGB)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
NameError: name 'cap' is not defined
>>> facesCurFrame = face_recognition.face_locations(imgS)
File "<stdin>", line 1
facesCurFrame = face_recognition.face_locations(imgS)
IndentationError: unexpected indent
>>> encodeCurFrame = face_recognition.face_encodings(imgS, facesCurFrame)
File "<stdin>", line 1
encodeCurFrame = face_recognition.face_encodings(imgS, facesCurFrame)
IndentationError: unexpected indent
>>>
>>> for encodeFace, faceLoc in zip(encodeCurFrame, facesCurFrame):
File "<stdin>", line 1
for encodeFace, faceLoc in zip(encodeCurFrame, facesCurFrame):
IndentationError: unexpected indent
>>> matches = face_recognition.compare_faces(encodeListKnown, encodeFace)
File "<stdin>", line 1
matches = face_recognition.compare_faces(encodeListKnown, encodeFace)
IndentationError: unexpected indent
>>> faceDis = face_recognition.face_distance(encodeListKnown, encodeFace)
File "<stdin>", line 1
faceDis = face_recognition.face_distance(encodeListKnown, encodeFace)
IndentationError: unexpected indent
>>> #print(faceDis)
>>> matchIndex = np.argmin(faceDis)
File "<stdin>", line 1
matchIndex = np.argmin(faceDis)
IndentationError: unexpected indent
>>>
>>> if matches[matchIndex]:
File "<stdin>", line 1
if matches[matchIndex]:
IndentationError: unexpected indent
>>> name = classNames[matchIndex]
File "<stdin>", line 1
name = classNames[matchIndex]
IndentationError: unexpected indent
>>> #print(name)
>>> y1, x2, y2, x1 = faceLoc
File "<stdin>", line 1
y1, x2, y2, x1 = faceLoc
IndentationError: unexpected indent
>>> y1, x2, y2, x1 = y1 * 4, x2 * 4, y2 * 4, x1 * 4
File "<stdin>", line 1
y1, x2, y2, x1 = y1 * 4, x2 * 4, y2 * 4, x1 * 4
IndentationError: unexpected indent
>>> cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
File "<stdin>", line 1
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
IndentationError: unexpected indent
>>> cv2.rectangle(img, (x1, y2 - 35), (x2, y2), (0, 255, 0), cv2.FILLED)
File "<stdin>", line 1
cv2.rectangle(img, (x1, y2 - 35), (x2, y2), (0, 255, 0), cv2.FILLED)
IndentationError: unexpected indent
>>> cv2.putText(img, name, (x1 + 6, y2 - 6), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)
File "<stdin>", line 1
cv2.putText(img, name, (x1 + 6, y2 - 6), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)
IndentationError: unexpected indent
>>> markAttendance(name)
File "<stdin>", line 1
markAttendance(name)
IndentationError: unexpected indent
>>>
>>> cv2.imshow("WebCam", img)
File "<stdin>", line 1
cv2.imshow("WebCam", img)
IndentationError: unexpected indent
>>> cv2.waitKey(1)
ОШИБКА ПОЧТИ В КАЖДОЙ СТРОЧКЕ! Но я так понимаю что это из-за неподключённых библиотек, ведь так? Можете пожалуйста скинуть рабочий код для распознавания лиц в google colab’e?
0
Из-за потребностей проекта вам необходимо установить стороннюю библиотеку pydicom в pycharm. Этот модуль нельзя найти непосредственно в существующем интерпретаторе python (файл> настройки> Project Interpreter), поэтому введите команду в терминале:
pip install pydicom
успешно установлен, мой путь установки по умолчанию: «C: Users yf AppData Local Programs Python Python37 Lib site-packages»,
Вы можете найти установленный модуль «pydicom» по этому пути.

, но запускается в pycharm
import pydicom
сообщит
No module named 'pydicom',
Это означает, что недавно установленный модуль pydicom не был успешно импортирован в этот проект. Причина в том, что виртуальная среда текущего проекта не импортировала модуль, поэтому я использовал решение Решение состоит в том, чтобы воссоздать новую виртуальную среду и импортировать модуль.
Выберите «Project Interpreter» в pycharm и нажмите «Добавить»

Желтое поле (Расположение) представляет путь, в котором хранится созданная виртуальная среда. Обратите внимание, что последняя папка должна быть пустой, иначе виртуальная среда не может быть создана!
Синее поле (базовый интерпретатор) выбирает среду версии python, когда вы установили python!
Внимание! Красный квадрат означает отметку «Наследовать глобальные пакеты сайтов». На этом шаге необходимо импортировать только что установленный модуль «pydicom»! После настройки нажмите OK, чтобы завершить создание виртуальной среды python.

Выберите виртуальную среду, только что созданную в интерпретаторе python, вы увидите, что «pydicom» был импортирован в среду, запустите код
import pydicom,
не будет сообщать
No module named 'pydicom'Неправильно,
Проблема решена.
При изучении программирования на Python в среде разработки PyCharm (PC), у меня возникли проблемы с установкой модулей из менеджера библиотек PiP, поэтому немного разобравшись в проблеме, я решил написать эту статью:
- В среде разработки PyCharm нажимаем: меню File — Settings, Project: (имя проекта), Project interpreter, справа от списка установленных модулей жмем +, в поиске вводим «Название библиотеки/модуля», выбираем найденный модуль, потом внизу жмем Install Package.
- В окне Terminal вводим: «pip install название_модуля» (без » )
- Скачиваем библиотеку/модуль с сайта pypi.org и устанавливаем через Terminal в PyCharm указав полный путь к файлу: pip install C:/user/downloads/назв_мод.whl
Вариант 3 у меня был, когда я изучал уроки «Распознавание речи» с сайта itproger.com для установки модуля PyAudio, пришлось сначала скачать его на компьютер и только потом установить его указав путь к файлу на жестком диске «pip install С:/user/PyAudio‑0.2.11‑cp37‑cp37m‑win_amd64.whl «
Пишите в комментариях, если я что-то забыл указать!