- Installing Python ModulesВ¶
- Key termsВ¶
- Basic usageВ¶
- How do I …?¶
- … install pip in versions of Python prior to Python 3.4?¶
- … install packages just for the current user?¶
- … install scientific Python packages?¶
- … work with multiple versions of Python installed in parallel?¶
- Common installation issuesВ¶
- Installing into the system Python on LinuxВ¶
- Pip not installedВ¶
- Installing binary extensionsВ¶
- Install python modules/package using IDLE on Windows
- 6 Answers 6
- Шаг 5. Установка пакетов в окружении Python Step 5: Install packages in your Python environment
- Просмотр окружений View environments
- Установка пакетов с помощью окна «Окружения Python» Install packages using the Python Environments window
- Запуск программы Run the program
Installing Python ModulesВ¶
As a popular open source development project, Python has an active supporting community of contributors and users that also make their software available for other Python developers to use under open source license terms.
This allows Python users to share and collaborate effectively, benefiting from the solutions others have already created to common (and sometimes even rare!) problems, as well as potentially contributing their own solutions to the common pool.
This guide covers the installation part of the process. For a guide to creating and sharing your own Python projects, refer to the distribution guide .
For corporate and other institutional users, be aware that many organisations have their own policies around using and contributing to open source software. Please take such policies into account when making use of the distribution and installation tools provided with Python.
Key termsВ¶
pip is the preferred installer program. Starting with Python 3.4, it is included by default with the Python binary installers.
A virtual environment is a semi-isolated Python environment that allows packages to be installed for use by a particular application, rather than being installed system wide.
venv is the standard tool for creating virtual environments, and has been part of Python since Python 3.3. Starting with Python 3.4, it defaults to installing pip into all created virtual environments.
virtualenv is a third party alternative (and predecessor) to venv . It allows virtual environments to be used on versions of Python prior to 3.4, which either don’t provide venv at all, or aren’t able to automatically install pip into created environments.
The Python Packaging Index is a public repository of open source licensed packages made available for use by other Python users.
the Python Packaging Authority is the group of developers and documentation authors responsible for the maintenance and evolution of the standard packaging tools and the associated metadata and file format standards. They maintain a variety of tools, documentation, and issue trackers on both GitHub and Bitbucket.
distutils is the original build and distribution system first added to the Python standard library in 1998. While direct use of distutils is being phased out, it still laid the foundation for the current packaging and distribution infrastructure, and it not only remains part of the standard library, but its name lives on in other ways (such as the name of the mailing list used to coordinate Python packaging standards development).
Changed in version 3.5: The use of venv is now recommended for creating virtual environments.
Basic usageВ¶
The standard packaging tools are all designed to be used from the command line.
The following command will install the latest version of a module and its dependencies from the Python Packaging Index:
For POSIX users (including Mac OS X and Linux users), the examples in this guide assume the use of a virtual environment .
For Windows users, the examples in this guide assume that the option to adjust the system PATH environment variable was selected when installing Python.
It’s also possible to specify an exact or minimum version directly on the command line. When using comparator operators such as > , or some other special character which get interpreted by shell, the package name and the version should be enclosed within double quotes:
Normally, if a suitable module is already installed, attempting to install it again will have no effect. Upgrading existing modules must be requested explicitly:
More information and resources regarding pip and its capabilities can be found in the Python Packaging User Guide.
Creation of virtual environments is done through the venv module. Installing packages into an active virtual environment uses the commands shown above.
How do I …?¶
These are quick answers or links for some common tasks.
… install pip in versions of Python prior to Python 3.4?¶
Python only started bundling pip with Python 3.4. For earlier versions, pip needs to be “bootstrapped” as described in the Python Packaging User Guide.
… install packages just for the current user?¶
Passing the —user option to python -m pip install will install a package just for the current user, rather than for all users of the system.
… install scientific Python packages?¶
A number of scientific Python packages have complex binary dependencies, and aren’t currently easy to install using pip directly. At this point in time, it will often be easier for users to install these packages by other means rather than attempting to install them with pip .
… work with multiple versions of Python installed in parallel?¶
On Linux, Mac OS X, and other POSIX systems, use the versioned Python commands in combination with the -m switch to run the appropriate copy of pip :
Appropriately versioned pip commands may also be available.
On Windows, use the py Python launcher in combination with the -m switch:
Common installation issuesВ¶
Installing into the system Python on LinuxВ¶
On Linux systems, a Python installation will typically be included as part of the distribution. Installing into this Python installation requires root access to the system, and may interfere with the operation of the system package manager and other components of the system if a component is unexpectedly upgraded using pip .
On such systems, it is often better to use a virtual environment or a per-user installation when installing packages with pip .
Pip not installedВ¶
It is possible that pip does not get installed by default. One potential fix is:
There are also additional resources for installing pip.
Installing binary extensionsВ¶
Python has typically relied heavily on source based distribution, with end users being expected to compile extension modules from source as part of the installation process.
With the introduction of support for the binary wheel format, and the ability to publish wheels for at least Windows and Mac OS X through the Python Packaging Index, this problem is expected to diminish over time, as users are more regularly able to install pre-built extensions rather than needing to build them themselves.
Some of the solutions for installing scientific software that are not yet available as pre-built wheel files may also help with obtaining other binary extensions without needing to build them locally.
Install python modules/package using IDLE on Windows
I have a python script and begins as (just a part of it) —
Now, when I run it, it says missing requests module.
I’ve downloaded & installed 3 versions of Python from python.org, but still it seems that the packages are not installed. Can anyone tell me how to install modules using IDLE on Windows 7.
Versions I have — 2.7.8, 3.3.5, 3.4.2.
6 Answers 6
you can use pip(a package manager for python) to install dependencies . check this link : https://pip.pypa.io/en/latest/installing.html
Under present versions of Python (version 3.4 or above), do the following:
Windows
Linux
You can find Windows binaries for Python packages here:
It’s just install.
Or you can use pip:
Add pip to the system path and run commands on cmd, example:
More info to install pip:
In Windows you should, like in Linux, use the command prompt to install your packages using pip. However, for this to work the Python executable must be in the system path. Also, all your different versions of Python need the packages installed individually.
The issue is that in the installations of all the different versions of Python, all of them have a executable called python.exe i.e. same name!
Thus, you need to rename them, for example, to python27, python33, etc. to access them individually. By renaming them and calling «pythonXX» in cmd prompt this can be done, otherwise, cmd will just take the first instance of python.exe in the system path when «python» is called in cmd.
This is particularly problematic if Anaconda2 is also installed because all packages will just there. Once you are able to run your different versions of Python from the command line you should be able to install packages correctly using pip.
- Rename python.exe to pythonXX.exe
- Add the folder in which pythonXX.exe is located to the system path (see below)
- Start cmd prompt and write «pythonXX -m pip install -U pip» — This command updates pip. If it dosen’t work restart the computer to update path and try again.
- Now you should be able to install packages into the correct versions using pip.
- Note that you should write e.g. «pythonXX -m pip install -U scikit-learn» to install your libraty.
Once the packages are installed into the right folders, they should also be available from IDLE and you are ready to go.
To access system path in Windows
- Go to Control Panel
- Select “System” from the context menu.
- Click “Advanced system settings”
- Go to the “Advanced” tab
- Click “Environment Variables…”
- Click variable called “Path” and click “Edit…”
- Click “New”
- Enter the path to the folder containing the executable you want on your PATH. For example, to add python33.exe, add: «C:\Python33\» or what your path to python33.exe is.
Шаг 5. Установка пакетов в окружении Python Step 5: Install packages in your Python environment
Предыдущий шаг. Выполнение кода в отладчике Previous step: Run code in the debugger
Сообщество разработчиков на Python создало тысячи полезных пакетов, которые вы можете включать в свои проекты. The Python developer community has produced thousands of useful packages that you can incorporate into your own projects. В Visual Studio имеется пользовательский интерфейс для управления пакетами в средах Python. Visual Studio provides a UI to manage packages in your Python environments.
Просмотр окружений View environments
Выберите команду меню Просмотр > Другие окна > Окружения Python. Select the View > Other Windows > Python Environments menu command. Откроется окно Окружения Python (как узел обозревателя решений), в котором представлены разные среды, доступные вам. The Python Environments window opens as a peer to Solution Explorer and shows the different environments available to you. Список содержит как среды, установленные с помощью установщика Visual Studio, так и среды, которые вы установили отдельно. The list shows both environments that you installed using the Visual Studio installer and those you installed separately. В их число входят глобальные, виртуальные среды и среды Conda. That includes global, virtual, and conda environments. Среда, выделенная полужирным шрифтом, — это среда, используемая по умолчанию для новых проектов. The environment in bold is the default environment that’s used for new projects. Дополнительные сведения о работе со средами см. в разделе Создание окружений Python и управление ими в средах Visual Studio. For additional information about working with environments, see How to create and manage Python environments in Visual Studio environments.
Можно также открыть окно «Окружения Python», выбрав окно Обозревателя решений и нажав сочетание клавиш CTRL+K, CTRL+` . You can also open the Python Environments window by selecting the Solution Explorer window and using the Ctrl+K, Ctrl+` keyboard shortcut. Если сочетание клавиш не работает и окно «Окружения Python» отсутствует в меню, возможно, не установлена рабочая нагрузка Python. If the shortcut doesn’t work and you can’t find the Python Environments window in the menu, it’s possible you haven’t installed the Python workload. Инструкции по установке Python см. в статье Установка поддержки Python в Visual Studio. See How to install Python support in Visual Studio for guidance about how to install Python.
На вкладке Обзор среды можно быстро получить доступ к интерактивному окну этой среды, а также к ее папке установки и интерпретаторам. The environment’s Overview tab provides quick access to an Interactive window for that environment along with the environment’s installation folder and interpreters. Например, щелкните ссылку Открыть интерактивное окно, и в Visual Studio откроется интерактивное окно для этой среды. For example, select Open interactive window and an Interactive window for that specific environment appears in Visual Studio.
Теперь создайте проект, выбрав пункт меню Файл > Создать > Проект, а затем выбрав шаблон Приложение Python. Now, create a new project with File > New > Project, selecting the Python Application template. В появившийся файл кода вставьте приведенный ниже код, который строит косинусоиду, как в предыдущих шагах учебника, но теперь в виде графика. In the code file that appears, paste the following code, which creates a cosine wave like the previous tutorial steps, only this time plotted graphically. Кроме того, можно использовать ранее созданный проект и заменить код. Alternatively, you can use the project you previously created and replace the code.
В открытом проекте Python можно открыть окно «Окружения Python» из Обозревателя решений, щелкнув правой кнопкой мыши Окружения Python и выбрав Просмотреть все окружения Python. With a Python project open, you can also open the Python Environments window from Solution Explorer by right-clicking Python Environments and selecting View All Python Environments
Если в окне редактора вы наведете указатель мыши на операторы импорта numpy и matplotlib , вы заметите, что они не разрешены. Looking at the editor window, you’ll notice that if you hover over the numpy and matplotlib import statements that they are not resolved. Это связано с тем, что пакеты не были установлены в глобальную среду по умолчанию. That’s because the packages have not been installed to the default global environment.
Установка пакетов с помощью окна «Окружения Python» Install packages using the Python Environments window
В окне «Окружения Python» выберите среду по умолчанию для новых проектов Python и перейдите на вкладку Пакеты. На ней вы увидите список пакетов, установленных в настоящее время в среде. From the Python Environments window, select the default environment for new Python projects and choose the Packages tab. You will then see a list of packages that are currently installed in the environment.
Установите пакет matplotlib , введя его имя в поле поиска, а затем выбрав параметр Выполнить команду «pip install matplotlib» . Install matplotlib by entering its name into the search field and then selecting the Run command: pip install matplotlib option. Будет установлен пакет matplotlib , а также все пакеты, от которых он зависит (в данном случае — numpy ). This will install matplotlib , as well as any packages it depends on (in this case that includes numpy ).
Согласитесь на повышение прав, если появится соответствующий запрос. Consent to elevation if prompted to do so.
Установленный пакет появится в окне Окружения Python. After the package is installed, it appears in the Python Environments window. Если щелкнуть знак X справа от пакета, он будет удален. The X to the right of the package uninstalls it.
Под названием среды может появиться небольшой индикатор выполнения, который указывает на то, что Visual Studio создает базу данных IntelliSense для нового пакета. A small progress bar might appear underneath the environment to indicate that Visual Studio is building its IntelliSense database for the newly-installed package. На вкладке IntelliSense также приводятся более подробные сведения. The IntelliSense tab also shows more detailed information. Имейте в виду, что, пока база данных не будет готова, функции IntelliSense, такие как автозавершение и проверка синтаксиса, будут неактивны для этого пакета в редакторе. Be aware that until that database is complete, IntelliSense features like auto-completion and syntax checking won’t be active in the editor for that package.
В Visual Studio 2017 версии 15.6 и более поздних версий используются другие (более быстрые) методы для работы с IntelliSense. На вкладке IntelliSense отображается соответствующее сообщение. Visual Studio 2017 version 15.6 and later uses a different and faster method for working with IntelliSense, and displays a message to that effect on the IntelliSense tab.
Запуск программы Run the program
После установки matplotlib запустите программу с отладчиком (F5) или без него (CTRL+F5), чтобы увидеть результат. Now that matplotlib is installed, run the program with (F5) or without the debugger (Ctrl+F5) to see the output: