Pycharm ошибка при установке пакетов

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

  1. Press Ctrl+Alt+S to open the IDE settings and select .

  2. Expand the list of the available interpreters and click Show All.

    Show all available interpreters

  3. Locate the target interpreter and press edit interpreter.

    Discover the interpreter path for the selected venv

    Copy or memorize the path of the virtual environment and close the dialogs.

  4. Open the terminal and run the following commands:

    source <venv path>/bin/activate
    pip install <package name>

    Installing a Python package on a virtual environment

  5. Inspect and parse the results.

Install a package on a Conda environment

  1. 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.

    Installing a Python package on a virtual environment

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

    Fail to install a package on a Conda environment

  2. Inspect and parse the results.

Install a package on a system interpreter

  1. 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 .

  2. Expand the list of the project interpreters and scroll it down, then select the item.

    Selected Python interpreter

  3. Locate the interpreter and press edit interpreter.

    Discover the interpreter path for the selected venv

    Copy or memorize the path of the environment and close the dialogs.

  4. Open the terminal and run the following commands:

    cd <interpreter path>
    -m pip install <package name>

    Installing a Python package on a system environment

    You might need the admin privileges to install packages on a system interpreter.

  5. 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, sudo pip install <package name>.

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

I have pycharm community edition(latest stable build) installed on my Ubuntu 16.04 LTS, I am not able to install packages via pycharm, was able to install them before. I can install the packages via pip, but would like to solve this issue.

Below is the Screenshot of the problem

enter image description here

Have googled for this issue, but could not find any fix, I have a windows machine and it does not face the same issue.

asked Oct 15, 2016 at 14:37

penta's user avatar

pentapenta

2,5064 gold badges24 silver badges50 bronze badges

2

I have got a solution, i reffered to https://youtrack.jetbrains.com/issue/PY-20081#u=1468410176856.

Here they have tried to add https://pypi.python.org/pypi as a repository.

To add it as a repository,

1.) Go to Settings
2.) Project interpreter
3.) Click the + sign on top right edge
4.) Go to manage repositories, 
5.) Press the + Sign, then add https://pypi.python.org/pypi
6.) Press Ok

Now all the packages should load.

Thanks Hami Torun & Simon, I was able to solve it by luck.

answered Oct 15, 2016 at 16:23

penta's user avatar

pentapenta

2,5064 gold badges24 silver badges50 bronze badges

3

I had the same issue. It happened suddenly, day ago I was able to perform pip or install packages but on the next day error appeared. However this helped (I used version PyCharm Community Edition 2018):

Go to Settings -> Project Interpreter -> click green «+» icon (on right) -> Manage Repositories (on bottom) -> delete https://pypi.python.org/simple -> add https://pypi.python.org/pypi
then click Ok. Repo will be back again as /simple, but don’t worry, error should disappear and you should be able to install packages again.

answered May 2, 2018 at 14:58

Belloz's user avatar

BellozBelloz

4235 silver badges9 bronze badges

2

For me, it was because of low space in my pc. After I free up space the problem solved. Pycharm did not say anything about this problem. It just shows that «the package installed successfully», but actually package was not installed.

answered Apr 15, 2019 at 19:52

saleh sereshki's user avatar

saleh sereshkisaleh sereshki

2,3823 gold badges16 silver badges18 bronze badges

I just had a similar problem.
My project was created by PyCharm, with venv.
The package I was installing via manager (Ctrl+Alt+S), was showing in the list, but it wasn’t being recognized or imported.

I believe the error happened because I tried to install it before, using pip install into IDE’s own terminal. Also pip version in the manager was a beta version, then I changed it to a stable version.

Had to start a new project in a new folder.

answered Nov 2, 2020 at 0:20

Marcelo Assis's user avatar

Marcelo AssisMarcelo Assis

5,1363 gold badges33 silver badges54 bronze badges

The accepted answer didn’t work for me. I had to update my pip version from the PyCharm terminal:

pip install --upgrade pip

answered Dec 3, 2020 at 23:46

ezra buchla's user avatar

ezra buchlaezra buchla

3192 silver badges6 bronze badges

enter image description here

I installed PyCharm and and Python 3 using the zip file. Now I want to install various libraries but it would not allow me to do so. How should I install the libraries on PyCharm?

asked Jun 19, 2018 at 20:02

JungleDiff's user avatar

i think you need to install setuptools

sudo apt-get install python3-setuptools

answered Jun 19, 2018 at 20:04

Druta Ruslan's user avatar

Druta RuslanDruta Ruslan

7,1212 gold badges28 silver badges38 bronze badges

Important Step:

Open Command Prompt in Windows
And Type pip install python3-setuptools

If First Step is throwing some Error

To solve this,you need to let python know where the pip packages are to do this follow the instructions below

First Go to Settings and select Project interpreter, now Click on Add button and switch to manage repositories option and now again press add button and type
https://pypi.python.org/pypi in the box and save.

Now Restart your pycharm and it will work.

answered Jun 19, 2018 at 20:09

SaiKiran's user avatar

SaiKiranSaiKiran

6,16410 gold badges42 silver badges76 bronze badges

6

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 'numpy\distutils': '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

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

  1. Press Ctrl+Alt+S to open the IDE settings and select .

  2. Expand the list of the available interpreters and click Show All.

    Show all available interpreters

  3. Locate the target interpreter and press edit interpreter.

    Discover the interpreter path for the selected venv

    Copy or memorize the path of the virtual environment and close the dialogs.

  4. Open the terminal and run the following commands:

    source <venv path>/bin/activate
    pip install <package name>

    Installing a Python package on a virtual environment

  5. Inspect and parse the results.

Install a package on a Conda environment

  1. 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.

    Installing a Python package on a virtual environment

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

    Fail to install a package on a Conda environment

  2. Inspect and parse the results.

Install a package on a system interpreter

  1. 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 .

  2. Expand the list of the project interpreters and scroll it down, then select the item.

    Selected Python interpreter

  3. Locate the interpreter and press edit interpreter.

    Discover the interpreter path for the selected venv

    Copy or memorize the path of the environment and close the dialogs.

  4. Open the terminal and run the following commands:

    cd <interpreter path>
    -m pip install <package name>

    Installing a Python package on a system environment

    You might need the admin privileges to install packages on a system interpreter.

  5. 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, sudo pip install <package name>.

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import face-recognition #пробовал и face_recognition
import cv2
import numpy as np
import os
from datetime import datetime
 
path = 'KnownFaces'
images = []
classNames = []
myList = os.listdir(path)
print(myList)
 
for cls in myList:
    curImg = cv2.imread(f'{path}/{cls}')
    images.append(curImg)
    classNames.append(os.path.splitext(cls)[0])
 
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)
 
while True:
    success, img = cap.read()
    imgS = cv2.resize(img, (0, 0), None, 0.25, 0.25)
    imgS = cv2.cvtColor(imgS, cv2.COLOR_BGR2RGB)
 
    facesCurFrame = face_recognition.face_locations(imgS)
    encodeCurFrame = face_recognition.face_encodings(imgS, facesCurFrame)
 
    for encodeFace, faceLoc in zip(encodeCurFrame, facesCurFrame):
        matches = face_recognition.compare_faces(encodeListKnown, encodeFace)
        faceDis = face_recognition.face_distance(encodeListKnown, encodeFace)
        #print(faceDis)
        matchIndex = np.argmin(faceDis)
 
        if matches[matchIndex]:
            name = classNames[matchIndex]
            #print(name)
            y1, x2, y2, x1 = faceLoc
            y1, x2, y2, x1 = y1 * 4, x2 * 4, y2 * 4, x1 * 4
            cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
            cv2.rectangle(img, (x1, y2 - 35), (x2, y2), (0, 255, 0), cv2.FILLED)
            cv2.putText(img, name, (x1 + 6, y2 - 6), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)
            markAttendance(name)
 
    cv2.imshow("WebCam", img)
    cv2.waitKey(1)

Выводит следующее:

Код

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 Установка не удалась из-за проблем с сетью

  1. Перейдите на соответствующий веб-сайт и загрузите соответствующий файл whl. Соответствующий номер cp + в имени пакета представляет поддерживаемый формат. Соответствующий номер cp + в имени пакета представляет поддерживаемый формат.
  2. Затем переместите загруженный whl-файл в каталог сценариев локального python. В это время вам нужно выбрать каталог, в котором расположен ваш проект. Если это виртуальный каталог, вам нужно ввести каталог сценариев виртуального каталога. (Сеть виртуальных каталогов для этого компьютера: D: Anaconda3 envs network Scripts)
  3. pip intall «путь к файлу»

1.2 Сбой установки в Анаконде

Если он установлен вместе с conda install -n network dnspython3 (обратите внимание: последние два параметра основаны на вас самих, network — это виртуальный каталог, в котором находится мой проект, а dnspython3 — это имя устанавливаемого пакета), если на веб-сайте, связанном с Anaconda, этот пакет отсутствует, Затем он сообщит об ошибке, которая не может быть найдена.
выглядит следующим образом:

F: Информация Классы Сетевое программирование Программные средства memcached_en32or64 x64> conda install -n network d
nspython3 Solving environment: failed

PackagesNotFoundError: 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 to

https://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, что может эффективно избежать проблемы конфликтов имен, вызванных импортом сторонних пакетов.


  1. https://blog.csdn.net/kouyi5627/article/details/80531442
    end。 ↩︎

  • Python try except получить текст ошибки
  • Python логирование всех ошибок
  • Pycharm ошибка при установке библиотеки
  • Python try except печать ошибки
  • Python код ошибки 2503