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
Содержание
- Package installation issues
- Install a package using the Terminal
- Install a package on a virtual environment
- Install a package on a Conda environment
- Install a package on a system interpreter
- Parse the results
- Review typical cases
- How to Install Pytorch in Pycharm ? : Only 3 Steps
- How to test or check if Pytorch is installed or not?
- Other Questions Asked by the Reader
- Q 1: I am getting errors like no module named torch. How to solve this issue?
- Q 2. error occurred when installing package pycharm
- Similar Articles :
- How to Install Scikit Learn in Pycharm ? Only 5 Steps
- How to Install Pandas in Pycharm? : Only 4 Steps
- How to Install Scrapy in Pycharm : Install it in 5 Steps Only
- Join our list
- How to Install Python Packages in PyCharm Without Anaconda
- And solve a common error message by following a few simple steps
- How to Install Python Packages in PyCharm Without Anaconda
- How to Solve Error Messages While Installing Packages in PyCharm
- Conclusion
- Как правильно устанавливать библиотеки в PyCharm?
- VolodinAS
Package installation issues
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 Project
Expand the list of the available interpreters and click the Show All link.
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:
Install a package on a Conda environment
Open the terminal and run the following commands:
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.
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 Project:
Expand the list of the project interpreters and scroll it down, then select the Show All 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:
You might need the admin privileges to install packages on a system interpreter.
Parse the results
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, sudo pip install
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
fatal error: ‘SDL.h’ file not found
Installation fails because the package requires SDL, and pip cannot detect it. Try the following commands:
Cannot open include file: ‘portaudio.h’
Try to run the following commands using the admin privileges:
SSL module in Python is not available
Install an openssl library by the way specific to your operating system. See the detailed solutions.
Источник
How to Install Pytorch in Pycharm ? : Only 3 Steps
AssertionError: torch not compiled with cuda enabled ( Fix )
Pytorch is an Open source machine learning library that was developed by the Social Giant Facebook. You can do many things using it, like NLP, computer vision and deep learning, etc. But one thing you should be aware that its computations are similar to Numpy. The only difference is that Pytorch uses GPU for computation and Numpy uses CPU. This makes it fast. Most beginners are unable to properly install Pytorch in Pycharm In this tutorial on “How to” you will know how to install Pytorch in Pycharm. Just follow the simple steps for the proper installation of the Pytorch.
When you write import torch then you will see an error like the figure below (Red underline). It means Pytorch is not installed in Pycharm and you will get the error No module named torch when your run the code. So you have to install this module. Follow the below steps for installing it.
Step 1: Click on Setting and click on Project: Your Project Name
Go to File>>Setting and click on Project: Your_project_name. There you will see two options. Project Interpreter and Project Structure.
Step 2: Click on the Project Interpreter. There you will see all the installed packages. Pytorch is not there let’s install it.
Step 3: Click on the “+” sign and search for the PyTorch. You will see it, and its description on the right side. Select it and click on Install Package. This will install the Package. If an error comes then try to search for the torch and install it otherwise it is successfully installed.
If you are seeing an error like this “Error occurred when installing Package Pytorch“. Then you should install Pytorch through Pycharm Terminal.
Go to the Pyrcharm terminal and write the command
That’s all you have to do for installing Pytorch in Pycharm.
How to test or check if Pytorch is installed or not?
After installing the Pytorch, you can easily check its version. Just use the following code.
You will see the version info.
Other Questions Asked by the Reader
Q 1: I am getting errors like no module named torch. How to solve this issue?
No module named torch error is an import error. It generally occurs when you have not properly installed it in your system. To remove it you have to install it. If you are working on Pycharm then the above steps will solve these issues. Otherwise, you can install it manually. You can use the pip command to install it. First, update your pip command using the following commands.
After that install Pytorch using the pip command
For python 3. xx
For python 2. xx
It will remove the no module named PyTorch error.
Q 2. error occurred when installing package pycharm
If you are getting errors while installing the package in pycharm then try to update or change the python version. Also, update pycharm and the pip package. Then after installing the torch package. It will successfully install the package.
Similar Articles :
How to Install Scikit Learn in Pycharm ? Only 5 Steps
How to Install Pandas in Pycharm? : Only 4 Steps
How to Install Scrapy in Pycharm : Install it in 5 Steps Only
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
We respect your privacy and take protecting it seriously
Thank you for signup. A Confirmation Email has been sent to your Email Address.
Источник
How to Install Python Packages in PyCharm Without Anaconda
And solve a common error message by following a few simple steps
When I needed to use pandas, NumPy, matplotlib, and seaborn in PyCharm, it did not respond to my commands even though my environment was set to Conda and I was using Anaconda as a base interpreter.
This is what happened.
I wanted to use Selenium for a project in PyCharm and also install Pandas, NumPy, and other packages before I could get running. After trying the commands above, none of the packages were installed. I kept getting error messages.
Out of frustration, I complained about the issue to my Python tutor and asked, “Can’t I use Jupyter Notebook for the project?”
This was what my tutor — a Python developer with 20-plus years of experience — told me: “There are multiple editors and each suits a specific purpose. Jupyter is best suited for data science projects. PyCharm is an IDE [note the word ‘IDE’, not ‘editor’]. I would suggest you get comfortable with PyCharm.”
I returned to PyCharm.
When Anaconda stops working, you can’t install or use packages in PyCharm when you select Conda as the environment. All packages stop working.
This article will explore plan B. You will learn how to install packages in PyCharm without Anaconda and solve error messages that may occur while installing the packages.
First, download Python if you haven’t already.
How to Install Python Packages in PyCharm Without Anaconda
When you take Anaconda out of the picture, installing packages in PyCharm can be hard. For some reason, error messages appear on your screen. However, the people who created PyCharm made it easy to install packages in it — if you know how to go about it.
Before installing a package, make sure you have a strong internet connection.
To install a package:
- Create a project in PyCharm.
- Click on “File” at the top left-hand side of PyCharm. Click “Settings.” You will see “Project:…. (and the name of your project).” Click on it. Click on “Project Interpreter” (just opened on the right side).
- On the right-hand side, you will see a plus sign. Click on it. Inside the opened box at the top of the page, search for the name of the package you want to install. Choose the package from the list, then click on “Install Package” at the bottom of the page.
Note: After writing some words in the search box, you will start to see suggestions of package names starting with the words you enter. It is always good to select the package you want from the list of suggested packages to avoid misspelling a package name and thus not seeing the package you want to install.
An “Installation successful” message will be displayed at the bottom of the page… or did an error just occur? Don’t worry. I’ve got you covered.
How to Solve Error Messages While Installing Packages in PyCharm
If an error occurs while installing a package in PyCharm, it may be due to a new version of the “pip” package on your computer. You have to update it before a package will install.
- Go to “Project Interpreter.” Click on it. Find “pip” among the listed packages. Click on it once, and “pip” will be highlighted. On the right-hand side of the page, you will see an eye-like image. When you hover on it, it displays “Show Early Releases.”
- At the top of the eye-like image, there is a faint arrow pointing up. It displays “Upgrade” when you hover on it. Click on the arrow to upgrade “pip” to the latest version. Wait for the upgrade to finish.
After the upgrade is finished, search for the package you want to install as explained above.
Conclusion
Installing Python packages in PyCharm without Anaconda should be your plan B because, without Anaconda, you will have to install packages for every new project you do — even if a package has been installed for a different project before. This takes time.
But when Anaconda stops functioning, you can still get your work done fast by following the steps in this article.
Источник
Как правильно устанавливать библиотеки в PyCharm?
VolodinAS
Новичок
Здравствуйте, уважаемые форумчане. Я — новичок в python, не ругайтесь, пожалуйста.
Предварительные данные:
- Указать свою операционную систему — WINDOWS 10
- Указать версию Python — PYTHON 3.8.0
- Укажите версию библиотек с которыми работаете, вставьте в спойлер вывод команды pip list
Суть вопроса такова.
Через командную строку я установил нужные мне библиотеки.
Команды:
То есть, через IDLE всё работает.
Запускаю PyCharm, вставляю этот же код:
1AppDataLocalTemptmpttixcb_z:
Error in sitecustomize; set PYTHONVERBOSE for traceback:
SyntaxError: (unicode error) ‘utf-8’ codec can’t decode byte 0xef in position 0: invalid continuation byte (sitecustomize.py, line 7)
Running from numpy source directory.
setup.py:480: UserWarning: Unrecognized setuptools command, proceeding with generating Cython sources and expanding templates
run_build = parse_setuppy_commands()
Cythonizing sources
Error in sitecustomize; set PYTHONVERBOSE for traceback:
SyntaxError: (unicode error) ‘utf-8’ codec can’t decode byte 0xef in position 0: invalid continuation byte (sitecustomize.py, line 7)
Processing numpy/random_bounded_integers.pxd.in
Processing numpy/randombit_generator.pyx
Traceback (most recent call last):
File «C:UsersVolodinASAppDataLocalTemppycharm-packagingnumpytoolscythonize.py», line 59, in process_pyx
from Cython.Compiler.Version import version as cython_version
ModuleNotFoundError: No module named ‘Cython’
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File «C:UsersVolodinASAppDataLocalTemppycharm-packagingnumpytoolscythonize.py», line 235, in
main()
File «C:UsersVolodinASAppDataLocalTemppycharm-packagingnumpytoolscythonize.py», line 231, in main
find_process_files(root_dir)
File «C:UsersVolodinASAppDataLocalTemppycharm-packagingnumpytoolscythonize.py», line 222, in find_process_files
process(root_dir, fromfile, tofile, function, hash_db)
File «C:UsersVolodinASAppDataLocalTemppycharm-packagingnumpytoolscythonize.py», line 188, in process
processor_function(fromfile, tofile)
File «C:UsersVolodinASAppDataLocalTemppycharm-packagingnumpytoolscythonize.py», line 64, in process_pyx
raise OSError(‘Cython needs to be installed in Python as a module’)
OSError: Cython needs to be installed in Python as a module
Traceback (most recent call last):
File «D:DOCUMENTSПРОГРАММИРОВАНИЕPYTHONPROJECTSPYCHARMme2safeautocrackervenvlibsite-packagespip-19.0.3-py3.8.eggpip_vendorpep517_in_process.py», line 207, in
main()
File «D:DOCUMENTSПРОГРАММИРОВАНИЕPYTHONPROJECTSPYCHARMme2safeautocrackervenvlibsite-packagespip-19.0.3-py3.8.eggpip_vendorpep517_in_process.py», line 197, in main
json_out[‘return_val’] = hook(**hook_input[‘kwargs’])
File «D:DOCUMENTSПРОГРАММИРОВАНИЕPYTHONPROJECTSPYCHARMme2safeautocrackervenvlibsite-packagespip-19.0.3-py3.8.eggpip_vendorpep517_in_process.py», line 69, in prepare_metadata_for_build_wheel
return hook(metadata_directory, config_settings)
File «D:DOCUMENTSПРОГРАММИРОВАНИЕPYTHONPROJECTSPYCHARMme2safeautocrackervenvlibsite-packagessetuptools-40.8.0-py3.8.eggsetuptoolsbuild_meta.py», line 140, in prepare_metadata_for_build_wheel
File «D:DOCUMENTSПРОГРАММИРОВАНИЕPYTHONPROJECTSPYCHARMme2safeautocrackervenvlibsite-packagessetuptools-40.8.0-py3.8.eggsetuptoolsbuild_meta.py», line 210, in run_setup
File «D:DOCUMENTSПРОГРАММИРОВАНИЕPYTHONPROJECTSPYCHARMme2safeautocrackervenvlibsite-packagessetuptools-40.8.0-py3.8.eggsetuptoolsbuild_meta.py», line 126, in run_setup
File «setup.py», line 508, in
setup_package()
File «setup.py», line 488, in setup_package
generate_cython()
File «setup.py», line 285, in generate_cython
raise RuntimeError(«Running cythonize failed!»)
RuntimeError: Running cythonize failed!
Command «D:DOCUMENTSПРОГРАММИРОВАНИЕPYTHONPROJECTSPYCHARMme2safeautocrackervenvScriptspython.exe D:DOCUMENTSПРОГРАММИРОВАНИЕPYTHONPROJECTSPYCHARMme2safeautocrackervenvlibsite-packagespip-19.0.3-py3.8.eggpip_vendorpep517_in_process.py prepare_metadata_for_build_wheel C:UsersVOLODI
1AppDataLocalTemptmpttixcb_z» failed with error code 1 in C:UsersVolodinASAppDataLocalTemppycharm-packagingnumpy
Помогите, пожалуйста, решить проблему. Пытался гуглить, но так и не нашел нужного решения. Не понимаю, PyCharm не использует ранее установленные библиотеки?
Источник
Уведомления
- Начало
- » Инструментальные средства разработки
- » Pycharm и установка PIL в env
#1 Окт. 27, 2012 11:17:06
Pycharm и установка PIL в env
Здравствуйте.
Не могу разобраться, как установить PIL в PyCharm в созданное виртуальное окружение?
ОС Windows
Офлайн
- Пожаловаться
#2 Окт. 28, 2012 10:52:49
Pycharm и установка PIL в env
File -> Settings -> Projeсt Interpreter -> Configure Interpeters -> Выбираешь своё вирт. окр-е -> Снизу в таблице “Packages” тыкаешь кнопку Install -> в поле поиска пишешь PIL -> тыкаешь его в найденном списке -> Install Package =) Сам же мог сделать…
Отредактировано buddha (Окт. 28, 2012 10:52:57)
Офлайн
- Пожаловаться
#3 Окт. 28, 2012 13:27:45
Pycharm и установка PIL в env
Конечно сам мог бы сделать, если бы PIL устанавливался так, как вы написали. Однако, он выдает ошибку “Install packages failed: Error occurred when installing package PIL.” И если без виртуального окружения я его поставил через exe, скачанный с сайта, то для виртуального окружения я не знаю как решить проблему
Отредактировано maksyun (Окт. 28, 2012 13:28:14)
Офлайн
- Пожаловаться
#4 Окт. 28, 2012 18:57:32
Pycharm и установка PIL в env
У меня была постоянно проблема с установкой pil на ubuntu. У pil еще есть зависимости.
Там всё сводилось к тому, что нужно было вручную скачивать пакеты для ubuntu, отвечающие за работу с изображениями.
На windows проблема та же, но вот решать нужно по другому, нежели в ubuntu. Я этого не делал…
Вот тебе статья для разминки =), вроде оно http://users.livejournal.com/__hedin/216279.html
Офлайн
- Пожаловаться
#6 Окт. 28, 2012 19:38:02
Pycharm и установка PIL в env
Спасибо, видимо придется скачивать исходники и через консоль в виртуальное окружение самому ставить, раз PyCharm не хочет
Офлайн
- Пожаловаться
#7 Окт. 28, 2012 20:19:23
Pycharm и установка PIL в env
Думаю, то что ты через консоль установил , не значит что всё ок.
Наверняка эта же проблема вскроется чуть позже…
Ну уже знаешь куда глядеть, так что разберешься
Офлайн
- Пожаловаться
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
Collecting tmtoolkit
Downloading tmtoolkit-0.1.6-py2.py3-none-any.whl (15.3MB)
Collecting pandas (from tmtoolkit)
Downloading pandas-0.21.0.tar.gz (11.3MB)
Complete output from command python setup.py egg_info:
Running from numpy source directory.
C:Users5A86~1AppDataLocalTempeasy_install-bz49tq70numpy-1.13.3setup.py:367: UserWarning: Unrecognized setuptools command, proceeding with generating Cython sources and expanding templates
run_build = parse_setuppy_commands()
C:Users5A86~1AppDataLocalTempeasy_install-bz49tq70numpy-1.13.3numpydistutilssystem_info.py:572: UserWarning:
Atlas (http://math-atlas.sourceforge.net/) libraries not found.
Directories to search for the libraries can be specified in the
numpy/distutils/site.cfg file (section [atlas]) or by setting
the ATLAS environment variable.
self.calc_info()
C:Users5A86~1AppDataLocalTempeasy_install-bz49tq70numpy-1.13.3numpydistutilssystem_info.py:572: UserWarning:
Blas (http://www.netlib.org/blas/) libraries not found.
Directories to search for the libraries can be specified in the
numpy/distutils/site.cfg file (section [blas]) or by setting
the BLAS environment variable.
self.calc_info()
non-existing path in 'numpydistutils': 'site.cfg'
C:Users5A86~1AppDataLocalTempeasy_install-bz49tq70numpy-1.13.3numpydistutilssystem_info.py:572: UserWarning:
Lapack (http://www.netlib.org/lapack/) libraries not found.
Directories to search for the libraries can be specified in the
numpy/distutils/site.cfg file (section [lapack]) or by setting
the LAPACK environment variable.
self.calc_info()
C:Users5A86~1AppDataLocalTempeasy_install-bz49tq70numpy-1.13.3numpydistutilssystem_info.py:572: UserWarning:
Lapack (http://www.netlib.org/lapack/) sources not found.
Directories to search for the sources can be specified in the
numpy/distutils/site.cfg file (section [lapack_src]) or by setting
the LAPACK_SRC environment variable.
self.calc_info()
C:Python34libdistutilsdist.py:260: UserWarning: Unknown distribution option: 'define_macros'
warnings.warn(msg)
Traceback (most recent call last):
File "C:Python34libdistutilscore.py", line 148, in setup
dist.run_commands()
File "C:Python34libdistutilsdist.py", line 955, in run_commands
self.run_command(cmd)
File "C:Python34libdistutilsdist.py", line 974, in run_command
cmd_obj.run()
File "C:Python34libsite-packagessetuptoolscommandbdist_egg.py", line 161, in run
self.run_command("egg_info")
File "C:Python34libdistutilscmd.py", line 313, in run_command
self.distribution.run_command(command)
File "C:Python34libdistutilsdist.py", line 974, in run_command
cmd_obj.run()
File "C:Users5A86~1AppDataLocalTempeasy_install-bz49tq70numpy-1.13.3numpydistutilscommandegg_info.py", line 26, in run
File "C:Python34libdistutilscmd.py", line 313, in run_command
self.distribution.run_command(command)
File "C:Python34libdistutilsdist.py", line 974, in run_command
cmd_obj.run()
File "C:Users5A86~1AppDataLocalTempeasy_install-bz49tq70numpy-1.13.3numpydistutilscommandbuild_src.py", line 148, in run
File "C:Users5A86~1AppDataLocalTempeasy_install-bz49tq70numpy-1.13.3numpydistutilscommandbuild_src.py", line 159, in build_sources
File "C:Users5A86~1AppDataLocalTempeasy_install-bz49tq70numpy-1.13.3numpydistutilscommandbuild_src.py", line 294, in build_library_sources
File "C:Users5A86~1AppDataLocalTempeasy_install-bz49tq70numpy-1.13.3numpydistutilscommandbuild_src.py", line 377, in generate_sources
File "numpycoresetup.py", line 672, in get_mathlib_info
'pandas.tests',
File "C:Python34libdistutilscommandconfig.py", line 243, in try_link
self._check_compiler()
File "C:Users5A86~1AppDataLocalTempeasy_install-bz49tq70numpy-1.13.3numpydistutilscommandconfig.py", line 51, in _check_compiler
File "C:Users5A86~1AppDataLocalTempeasy_install-bz49tq70numpy-1.13.3numpydistutilsmsvccompiler.py", line 50, in initialize
File "C:Python34libdistutilsmsvc9compiler.py", line 371, in initialize
vc_env = query_vcvarsall(VERSION, plat_spec)
File "C:Python34libsite-packagessetuptoolsmsvc.py", line 147, in msvc9_query_vcvarsall
return EnvironmentInfo(arch, ver).return_env()
File "C:Python34libsite-packagessetuptoolsmsvc.py", line 1228, in return_env
[self.VCIncludes,
File "C:Python34libsite-packagessetuptoolsmsvc.py", line 877, in VCIncludes
return [os.path.join(self.si.VCInstallDir, 'Include'),
File "C:Python34libsite-packagessetuptoolsmsvc.py", line 556, in VCInstallDir
raise distutils.errors.DistutilsPlatformError(msg)
distutils.errors.DistutilsPlatformError: Microsoft Visual C++ 10.0 is required. Get it with "Microsoft Windows SDK 7.1": www.microsoft.com/download/details.aspx?id=8279
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:Python34libsite-packagessetuptoolssandbox.py", line 158, in save_modules
yield saved
File "C:Python34libsite-packagessetuptoolssandbox.py", line 199, in setup_context
yield
File "C:Python34libsite-packagessetuptoolssandbox.py", line 254, in run_setup
_execfile(setup_script, ns)
File "C:Python34libsite-packagessetuptoolssandbox.py", line 49, in _execfile
exec(code, globals, locals)
File "C:Users5A86~1AppDataLocalTempeasy_install-bz49tq70numpy-1.13.3setup.py", line 392, in <module>
def build_extension(self, ext):
File "C:Users5A86~1AppDataLocalTempeasy_install-bz49tq70numpy-1.13.3setup.py", line 384, in setup_package
self.check_cython_extensions(self.extensions)
File "C:Users5A86~1AppDataLocalTempeasy_install-bz49tq70numpy-1.13.3numpydistutilscore.py", line 169, in setup
File "C:Python34libsite-packagessetuptools__init__.py", line 129, in setup
return distutils.core.setup(**attrs)
File "C:Python34libdistutilscore.py", line 163, in setup
raise SystemExit("error: " + str(msg))
SystemExit: error: Microsoft Visual C++ 10.0 is required. Get it with "Microsoft Windows SDK 7.1": www.microsoft.com/download/details.aspx?id=8279
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:Python34libsite-packagessetuptoolscommandeasy_install.py", line 1104, in run_setup
run_setup(setup_script, args)
File "C:Python34libsite-packagessetuptoolssandbox.py", line 257, in run_setup
raise
File "C:Python34libcontextlib.py", line 77, in __exit__
self.gen.throw(type, value, traceback)
File "C:Python34libsite-packagessetuptoolssandbox.py", line 199, in setup_context
yield
File "C:Python34libcontextlib.py", line 77, in __exit__
self.gen.throw(type, value, traceback)
File "C:Python34libsite-packagessetuptoolssandbox.py", line 170, in save_modules
saved_exc.resume()
File "C:Python34libsite-packagessetuptoolssandbox.py", line 145, in resume
six.reraise(type, exc, self._tb)
File "C:Python34libsite-packagespkg_resources_vendorsix.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:Python34libsite-packagessetuptoolssandbox.py", line 158, in save_modules
yield saved
File "C:Python34libsite-packagessetuptools__init__.py", line 129, in setup
return distutils.core.setup(**attrs)
File "C:Python34libdistutilscore.py", line 163, in setup
raise SystemExit("error: " + str(msg))
SystemExit: error: Microsoft Visual C++ 10.0 is required. Get it with "Microsoft Windows SDK 7.1": www.microsoft.com/download/details.aspx?id=8279
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:UsersБлаблаблаAppDataLocalTemppycharm-packaging1pandas
Сделал это, запустил через терминал. Вот код
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
Collecting numpy
Using cached https://files.pythonhosted.org/pack…79828291f68aebfff1642be212ec/numpy-1.19.4.zip
Installing build dependencies: started
Installing build dependencies: finished with status ‘done’
Getting requirements to build wheel: started
Getting requirements to build wheel: finished with status ‘done’
Preparing wheel metadata: started
Preparing wheel metadata: finished with status ‘error’
Complete output from command D:DOCUMENTSПРОГРАММИРОВАНИЕPYTHONPROJECTSPYCHARMme2safeautocrackervenvScriptspython.exe D:DOCUMENTSПРОГРАММИРОВАНИЕPYTHONPROJECTSPYCHARMme2safeautocrackervenvlibsite-packagespip-19.0.3-py3.8.eggpip_vendorpep517_in_process.py prepare_metadata_for_build_wheel C:UsersVOLODI~1AppDataLocalTemptmpttixcb_z:
Error in sitecustomize; set PYTHONVERBOSE for traceback:
SyntaxError: (unicode error) ‘utf-8’ codec can’t decode byte 0xef in position 0: invalid continuation byte (sitecustomize.py, line 7)
Running from numpy source directory.
setup.py:480: UserWarning: Unrecognized setuptools command, proceeding with generating Cython sources and expanding templates
run_build = parse_setuppy_commands()
Cythonizing sources
Error in sitecustomize; set PYTHONVERBOSE for traceback:
SyntaxError: (unicode error) ‘utf-8’ codec can’t decode byte 0xef in position 0: invalid continuation byte (sitecustomize.py, line 7)
Processing numpy/random_bounded_integers.pxd.in
Processing numpy/randombit_generator.pyx
Traceback (most recent call last):
File «C:UsersVolodinASAppDataLocalTemppycharm-packagingnumpytoolscythonize.py», line 59, in process_pyx
from Cython.Compiler.Version import version as cython_version
ModuleNotFoundError: No module named ‘Cython’
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File «C:UsersVolodinASAppDataLocalTemppycharm-packagingnumpytoolscythonize.py», line 235, in <module>
main()
File «C:UsersVolodinASAppDataLocalTemppycharm-packagingnumpytoolscythonize.py», line 231, in main
find_process_files(root_dir)
File «C:UsersVolodinASAppDataLocalTemppycharm-packagingnumpytoolscythonize.py», line 222, in find_process_files
process(root_dir, fromfile, tofile, function, hash_db)
File «C:UsersVolodinASAppDataLocalTemppycharm-packagingnumpytoolscythonize.py», line 188, in process
processor_function(fromfile, tofile)
File «C:UsersVolodinASAppDataLocalTemppycharm-packagingnumpytoolscythonize.py», line 64, in process_pyx
raise OSError(‘Cython needs to be installed in Python as a module’)
OSError: Cython needs to be installed in Python as a module
Traceback (most recent call last):
File «D:DOCUMENTSПРОГРАММИРОВАНИЕPYTHONPROJECTSPYCHARMme2safeautocrackervenvlibsite-packagespip-19.0.3-py3.8.eggpip_vendorpep517_in_process.py», line 207, in <module>
main()
File «D:DOCUMENTSПРОГРАММИРОВАНИЕPYTHONPROJECTSPYCHARMme2safeautocrackervenvlibsite-packagespip-19.0.3-py3.8.eggpip_vendorpep517_in_process.py», line 197, in main
json_out[‘return_val’] = hook(**hook_input[‘kwargs’])
File «D:DOCUMENTSПРОГРАММИРОВАНИЕPYTHONPROJECTSPYCHARMme2safeautocrackervenvlibsite-packagespip-19.0.3-py3.8.eggpip_vendorpep517_in_process.py», line 69, in prepare_metadata_for_build_wheel
return hook(metadata_directory, config_settings)
File «D:DOCUMENTSПРОГРАММИРОВАНИЕPYTHONPROJECTSPYCHARMme2safeautocrackervenvlibsite-packagessetuptools-40.8.0-py3.8.eggsetuptoolsbuild_meta.py», line 140, in prepare_metadata_for_build_wheel
File «D:DOCUMENTSПРОГРАММИРОВАНИЕPYTHONPROJECTSPYCHARMme2safeautocrackervenvlibsite-packagessetuptools-40.8.0-py3.8.eggsetuptoolsbuild_meta.py», line 210, in run_setup
File «D:DOCUMENTSПРОГРАММИРОВАНИЕPYTHONPROJECTSPYCHARMme2safeautocrackervenvlibsite-packagessetuptools-40.8.0-py3.8.eggsetuptoolsbuild_meta.py», line 126, in run_setup
File «setup.py», line 508, in <module>
setup_package()
File «setup.py», line 488, in setup_package
generate_cython()
File «setup.py», line 285, in generate_cython
raise RuntimeError(«Running cythonize failed!»)
RuntimeError: Running cythonize failed!
—————————————-
Command «D:DOCUMENTSПРОГРАММИРОВАНИЕPYTHONPROJECTSPYCHARMme2safeautocrackervenvScriptspython.exe D:DOCUMENTSПРОГРАММИРОВАНИЕPYTHONPROJECTSPYCHARMme2safeautocrackervenvlibsite-packagespip-19.0.3-py3.8.eggpip_vendorpep517_in_process.py prepare_metadata_for_build_wheel C:UsersVOLODI~1AppDataLocalTemptmpttixcb_z» failed with error code 1 in C:UsersVolodinASAppDataLocalTemppycharm-packagingnumpy
О проблеме, из-за которой сторонние пакеты, установленные Python, не могут быть указаны в Pycharm
- 0 Введение
- Не удалось установить 1 пункт
- 1.1 Установка не удалась из-за проблем с сетью
- 1.2 Сбой установки в Анаконде
- 2 Установка прошла успешно, но в интерпретаторе Pycharm нет нового установленного пакета
- 3 Вновь установленный пакет появляется в интерпретаторе Pycharm, но на него нельзя ссылаться
0 Введение
Существует множество причин неудачной ссылки на сторонний пакет, установленный в Python, в Pycharm: следующие типичные проблемы: 1. Сбой установки pip, 2. Установка прошла успешно, но нет нового установленного интерпретатора Pycharm. Пакет, 3. Недавно установленный пакет появляется в интерпретаторе Pycharm, но на него нельзя ссылаться.
Не удалось установить 1 пункт
Существует также много ситуаций, когда установка pip завершается неудачно: 1. Сбой установки из-за проблем с сетью 2. Если установлена среда Anaconda, может возникнуть проблема при установке с помощью команды conda. :
1.1 Установка не удалась из-за проблем с сетью
- Перейдите на соответствующий веб-сайт и загрузите соответствующий файл whl. Соответствующий номер cp + в имени пакета представляет поддерживаемый формат. Соответствующий номер cp + в имени пакета представляет поддерживаемый формат.
- Затем переместите загруженный whl-файл в каталог сценариев локального python. В это время вам нужно выбрать каталог, в котором расположен ваш проект. Если это виртуальный каталог, вам нужно ввести каталог сценариев виртуального каталога. (Сеть виртуальных каталогов для этого компьютера: D: Anaconda3 envs network Scripts)
- pip intall «путь к файлу»
1.2 Сбой установки в Анаконде
Если он установлен вместе с conda install -n network dnspython3 (обратите внимание: последние два параметра основаны на вас самих, network — это виртуальный каталог, в котором находится мой проект, а dnspython3 — это имя устанавливаемого пакета), если на веб-сайте, связанном с Anaconda, этот пакет отсутствует, Затем он сообщит об ошибке, которая не может быть найдена.
выглядит следующим образом:
F: Информация Классы Сетевое программирование Программные средства memcached_en32or64 x64> conda install -n network d
nspython3 Solving environment: failedPackagesNotFoundError: The following packages are not available from
current cha nnels:
- dnspython3
Current channels:
- https://repo.anaconda.com/pkgs/main/win-64
- https://repo.anaconda.com/pkgs/main/noarch
- https://repo.anaconda.com/pkgs/free/win-64
- https://repo.anaconda.com/pkgs/free/noarch
- https://repo.anaconda.com/pkgs/r/win-64
- https://repo.anaconda.com/pkgs/r/noarch
- https://repo.anaconda.com/pkgs/pro/win-64
- https://repo.anaconda.com/pkgs/pro/noarch
- https://repo.anaconda.com/pkgs/msys2/win-64
- https://repo.anaconda.com/pkgs/msys2/noarch
To search for alternate channels that may provide the conda package
you’re looking for, navigate tohttps://anaconda.org
and use the search bar at the top of the page.
В настоящее время вам необходимо войти в сеть виртуальной среды и установить ее с помощью команды pip. Следующим образом:
F: Data Classes Network Programming Software Tools> активировать сеть
(сеть) F: материалы классы сетевое программирование программные инструменты> pip install dnspython3
После успешной установки отобразятся:
Successfully built dnspython3 Installing collected packages:
dnspython, dnspython3 Successfully installed dnspython-1.15.0
dnspython3-1.15.0
Как определить, успешно ли установлен пакет?
Сторонние пакеты обычно устанавливаются в каталог ** Lib site-packages. Если вы можете найти имя пакета, которое вы только что установили в этом каталоге, это означает, что пакет был установлен Установка прошла успешно.
Если определено, что пакет был успешно установлен, и запрашивается при использовании в Pycharm:
AttributeError: module ‘dns’ has no attribute ‘resolver’
или
ModuleNotFoundError: No module named ‘dns.resolver’
Подобная ошибка указывает на то, что у Pycharm нет этого пакета в интерпретаторе, в котором находится текущий проект, поэтому вам необходимо проверить, правильно ли интерпретатор вашего проекта. Если вы используете виртуальный каталог и ваш pip установлен в среде вашей системы по умолчанию, это вызовет эту проблему.
Если pip установлен в системной среде по умолчанию, которая является так называемой общедоступной средой, нажмите «Файл» -> «Настройка», затем действуйте, как показано на рисунке ниже, щелкните значок «плюс» в правой части рисунка, Просто добавьте и найдите только что установленный пакет.
Здесь из-за версии пакета, от которого зависит проект Python, все авторы настоятельно рекомендуют использовать для проекта виртуальный каталог, и все установки выполняются только в текущем виртуальном каталоге, предпочтительно не в среде по умолчанию.
Конечно, есть и другие решения, вы можете обратиться к этой статье:После того, как Python установит пакет через pip в терминале, решение по-прежнему не может быть использовано в Pycharm.1В этом случае автор дает три решения, выбирайте любое из них.
3 Вновь установленный пакет появляется в интерпретаторе Pycharm, но на него нельзя ссылаться
Если в интерпретаторе, где находится текущий проект Pycharm, только что установленный пакет появился, но на него все еще нельзя ссылаться, проблема может быть в следующем:
В вашем текущем проекте уже есть модуль или каталог,Совпадает с именем модуля установочного пакетаВызвано конфликтом.
Например, автору необходимо установить пакет dnspython3, и он был успешно установлен следующим образом:
Кроме того, убедитесь, что он появился в интерпретаторе проекта (указывая, что Pycharm загрузил этот пакет), следующим образом:
В настоящее время импорт dns по-прежнему будет запрашивать отсутствие такого модуля, поскольку в моем проекте уже есть каталог dns, поэтому при импорте он будет иметь приоритет при импорте dns в ваш проект следующим образом. :
В настоящее время измените имя своего собственного каталога DNS, чтобы разрешить конфликт. Как показано ниже:
На этом этапе рекомендуется, чтобы при разработке проекта лучше всего было добавить префикс проекта к собственному имени каталога, например, от dns к net_dns, что может эффективно избежать проблемы конфликтов имен, вызванных импортом сторонних пакетов.
-
https://blog.csdn.net/kouyi5627/article/details/80531442
end。 ↩︎