How to install python module
How to install python module
How to Install a Python Module?
A module helps you to arrange your Python code logically. The code is easier to understand and use when it is organized into modules. You can bind and reference a module, which is a Python object with arbitrarily named attributes.
A module is simply a file containing Python code. Functions, groups, and variables can all be described in a module. Runnable code can also be used in a module. A module can be imported by multiple programs for their application, hence a single code can be used by multiple programs to get done with their functionalities faster and reliably.
Installing Python modules on Windows
Check pip is installed or not: To check whether pip is installed or not, run the following command in windows using the command prompt:
Output:
Output version should be equal or greater than 19 version, If not use the following command to update pip:
Output:
To install the pip package use the following command to install the required package:
To install the packages from the other resources, use the following command :
To upgrade the packages that are already installed, use the following command:
To uninstall a package that is already installed, use the following command:
Installing Python modules on Unix/macOS
Make sure that you have pip installed. Type the below command in your terminal verify if the pip is installed or not.
Note: If the pip is not installed then refer to the article
To update the installed pip and setup tools copies use the following command:
Type the below command to install the module using pip.
To install the specific version of the module use the following command:
To install the version of a module in between any two numbers:
To install a specific compatible version of full length:
To upgrade the project version use the following command:
To install a required module that is in the text document:
To install the directories that are present in the local system use the following command:
Manual installation of Python packages
The majority of Python packages are now designed to work with pip. If you have a kit that isn’t compatible, you’ll have to install it manually.
Install the kit by downloading it and then extracting it to a local directory. If the kit has its own set of installation instructions, obey them, if the package is not present there then use the following command to install the package using the command manually:
Python
Learn Python Programming
How to install modules
Python modules allow you to use code of others in your code. This saves you a lot of development time, you don’t have to reinvent the wheel each time.
There are thousands of modules available for Python, which save you time when developing. There are two ways to install Python modules: system wide and using a virtual environment.
Introduction modules
In Python you have amny code packages or code modules that are available. By using a module you don’t have to implement existing code again and you can use code made by other people.
This makes developing much easier, as you can save time with basic tasks like scraping a webpage or reading a CSV file.
If you search for a problem, you often find modules that you haven’t seen before or that simply aren’t available on your computer. You can install these modules on your computer and then use them.
You can load modules by importing them at the beginning of your code. For instance
Install module
You can install modules or packages with the Python package manager (pip). To install a module system wide, open a terminal and use the pip command. If you type the code below it will install the module.
That will install a Python module automatically. Generally you do not install modules system wide, but use a virtual environment or venv.
In order for this to work, you need to have pip installed. The installation process depends on your platform.
pip on Linux
You can get the pip package manager by following two commands. It will download an installation script with curl and then install it using Python.
If you use Ubuntu or Debian Linux you may also be able use the systems package manager:
pip on Windows
Make sure you have Python 3.4 or newer, because it ships with pip. If pip is not available and you use Python > 3.4+, just run the command:
You can check your version with the command
pip on macOS
To install pip on Apple Mac OS X, open up a terminal.
Then download the get-pip.py installation file with curl
You can then run the installation script:
That’s it, pip is now installed.
older versions of Python
For older versions of Python, it’s recommended that you upgrade instead of work with a legacy version of Python. If you insist, download the install script and place it in your Python directory. Then run it with
To do this, you need an administrator command prompt.
Virtualenv
We can create a virtual environemnt, that is seperate from the operating system. This allows you to use the same Python modules as other developers in your team.
Create a virtual environment with the line:
You now have 3 directories: bin, include and lib.
Move up a directory.
To activate the virtual environment type:
Distributing 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.
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В¶
the Python Package Index is a public repository of open source licensed packages made available for use by other Python users
the Python Packaging Authority are 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).
setuptools is a (largely) drop-in replacement for distutils first published in 2004. Its most notable addition over the unmodified distutils tools was the ability to declare dependencies on other packages. It is currently recommended as a more regularly updated alternative to distutils that offers consistent support for more recent packaging standards across a wide range of Python versions.
wheel (in this context) is a project that adds the bdist_wheel command to distutils /setuptools. This produces a cross platform binary packaging format (called “wheels” or “wheel files” and defined in PEP 427) that allows Python libraries, even those including binary extensions, to be installed on a system without needing to be built locally.
Open source licensing and collaborationВ¶
In most parts of the world, software is automatically covered by copyright. This means that other developers require explicit permission to copy, use, modify and redistribute the software.
Open source licensing is a way of explicitly granting such permission in a relatively consistent way, allowing developers to share and collaborate efficiently by making common solutions to various problems freely available. This leaves many developers free to spend more time focusing on the problems that are relatively unique to their specific situation.
The distribution tools provided with Python are designed to make it reasonably straightforward for developers to make their own contributions back to that common pool of software if they choose to do so.
The same distribution tools can also be used to distribute software within an organisation, regardless of whether that software is published as open source software or not.
Installing the toolsВ¶
The standard library does not include build tools that support modern Python packaging standards, as the core development team has found that it is important to have standard tools that work consistently, even on older versions of Python.
The currently recommended build and distribution tools can be installed by invoking the pip module at the command line:
For Windows users, these instructions assume that the option to adjust the system PATH environment variable was selected when installing Python.
The Python Packaging User Guide includes more details on the currently recommended tools.
Reading the Python Packaging User GuideВ¶
The Python Packaging User Guide covers the various key steps and elements involved in creating and publishing a project:
How do I…?¶
These are quick answers or links for some common tasks.
… choose a name for my project?¶
This isn’t an easy topic, but here are a few tips:
check the Python Package Index to see if the name is already in use
check popular hosting sites like GitHub, Bitbucket, etc to see if there is already a project with that name
check what comes up in a web search for the name you’re considering
avoid particularly common words, especially ones with multiple meanings, as they can make it difficult for users to find your software when searching for it
… create and distribute binary extensions?¶
This is actually quite a complex topic, with a variety of alternatives available depending on exactly what you’re aiming to achieve. See the Python Packaging User Guide for more information and recommendations.
Как устанавливать пакеты в Python — с PIP и без
Прежде чем что-то устанавливать, давайте разберёмся, что такое пакет, чем он отличается от модуля, и как с ним работать. У слова «пакет» применительно к Python два значения.
Установка PIP для Python 3 и 2
Если вы используете виртуальные окружения на базе venv или virtualenv, pip уже установлен. Начиная с Python 3.4 (для Python 2 — с версии 2.7.9) pip поставляется вместе с интерпретатором. Для более ранних версий устанавливать менеджер пакетов нужно вручную. Вариантов два:
C помощью скрипта get_pip.py — быстро.
Через setuptools — кроме pip сможем использовать easy_install.
Вариант 1. Скачиваем скрипт get_pip.py и запускаем в консоли. Для этого открываем терминал через Win+R>»cmd»>OK и пишем:
Полный путь полезен и в том случае, если у вас на компьютере несколько версий Python и вы ставите пакет для одной из них.
Вариант 2. Скачиваем архив с setuptools из PYPI и распаковываем в отдельный каталог. В терминале переходим в директорию setuptools c файлом setup.py и пишем:
python setup.py install
Установка пакета в pip
Пора запустить pip в Python и начать устанавливать пакеты короткой командой из консоли:
pip install имя_пакета
Обновить пакет не сложнее:
Если у вас последняя версия пакета, но вы хотите принудительно переустановить его:
Посмотреть список установленных пакетов Python можно с помощью команды:
Найти конкретный пакет по имени можно командой «pip search». О других командах можно прочесть в справке, которая выдается по команде «pip help».
Удаление пакета Python
Когда пакет больше не нужен, пишем:
pip uninstall имя_пакета
Как установить пакеты в Python без pip
он не удаляет пакеты,
он может пытаться установить недозагруженный пакет.
Если нужно скачать пакет из альтернативного источника, вы можете задать URL или локальный адрес на компьютере:
Список пакетов, установленных через easy_install, хранится в файле easy-install.pth в директории /libs/site-packages/ вашего Python.
К счастью, удалять установленные через easy_install пакеты можно с помощью pip. Если же его нет, потребуется удалить пакет вручную и стереть сведения о нем из easy-install.pth.
Теперь вы умеете ставить и удалять пакеты для вашей версии Python.
Кстати, для тех, кто изучает Python, мы подготовили список полезных и практичных советов.
Прежде чем что-то устанавливать, давайте разберёмся, что такое пакет, чем он отличается от модуля, и как с ним работать. У слова «пакет» применительно к Python два значения.
Установка PIP для Python 3 и 2
Если вы используете виртуальные окружения на базе venv или virtualenv, pip уже установлен. Начиная с Python 3.4 (для Python 2 — с версии 2.7.9) pip поставляется вместе с интерпретатором. Для более ранних версий устанавливать менеджер пакетов нужно вручную. Вариантов два:
C помощью скрипта get_pip.py — быстро.
Через setuptools — кроме pip сможем использовать easy_install.
Вариант 1. Скачиваем скрипт get_pip.py и запускаем в консоли. Для этого открываем терминал через Win+R>»cmd»>OK и пишем:
Полный путь полезен и в том случае, если у вас на компьютере несколько версий Python и вы ставите пакет для одной из них.
Вариант 2. Скачиваем архив с setuptools из PYPI и распаковываем в отдельный каталог. В терминале переходим в директорию setuptools c файлом setup.py и пишем:
python setup.py install
Установка пакета в pip
Пора запустить pip в Python и начать устанавливать пакеты короткой командой из консоли:
pip install имя_пакета
Обновить пакет не сложнее:
Если у вас последняя версия пакета, но вы хотите принудительно переустановить его:
Посмотреть список установленных пакетов Python можно с помощью команды:
Найти конкретный пакет по имени можно командой «pip search». О других командах можно прочесть в справке, которая выдается по команде «pip help».
Удаление пакета Python
Когда пакет больше не нужен, пишем:
pip uninstall имя_пакета
Как установить пакеты в Python без pip
он не удаляет пакеты,
он может пытаться установить недозагруженный пакет.
Если нужно скачать пакет из альтернативного источника, вы можете задать URL или локальный адрес на компьютере:
Список пакетов, установленных через easy_install, хранится в файле easy-install.pth в директории /libs/site-packages/ вашего Python.
К счастью, удалять установленные через easy_install пакеты можно с помощью pip. Если же его нет, потребуется удалить пакет вручную и стереть сведения о нем из easy-install.pth.
Теперь вы умеете ставить и удалять пакеты для вашей версии Python.
Кстати, для тех, кто изучает Python, мы подготовили список полезных и практичных советов.
Programming Historian
Installing Python Modules with pip
Fred Gibbs
There are many ways to install external python libraries; this tutorial explains one of the most common methods using pip.
edited by
reviewed by
published
modified
difficulty
Donate today!
Great Open Access tutorials cost money to produce. Join the growing number of people supporting Programming Historian so we can continue to share knowledge free of charge.
Contents
Lesson Goals
This lesson shows you how to download and install Python modules. There are many ways to install external modules, but for the purposes of this lesson, we’re going to use a program called pip, easily installable on mac/linux and windows. As of Python 2.7.9 and newer, pip is installed by default. This tutorial will be helpful for anyone using older versions of Python (which are still quite common).
Introducing Modules
One of the great things about using Python is the number of fantastic code libraries that are widely and easily available that can save you a lot of coding, or simply make a particular task (like creating a CSV file, or scraping a webpage) much easier. When Googling for solutions to problems, you’ll often find sample code that uses code libraries you haven’t heard about before. Don’t let these scare you away! Once these libraries are installed on your computer, you can use them by importing them at the beginning of your code; you can import as many libraries as you’d like, such as
For new Python users, it can be a bit intimidating to download and install external modules for the first time. There are many ways of doing it (thus adding to the confusion); this lesson introduces one of the easiest and most common ways of installing python modules.
The goal here is to install software on your computer that can automatically download and install Python modules for us. We’re going to use a program called pip.
Note: As of Python 3.4, pip will be included in the regular install. There are many reasons why you might not have this version yet, and in case you don’t, these instructions should help.
Mac and Linux instructions
As per the pip documentation, we can download a python script to install pip for us. Using a Mac or Linux, we can install pip via the command line by using the curl command, which downloads the pip installation perl script.
once you’ve downloaded the get-pip.py file, you need to execute it with the python interpreter. However, if you try to execute the script with python like
the script will most likely fail because it won’t have permissions to update certain directories on your filesystem that are by default set so that random scripts cannot change important files and give you viruses. In this case—and in all cases where you need to allow a script that you trust to write to your system folders—you can use the sudo command (short for “Super User DO”) in front of the python command, like
Windows Instructions
As with the above platforms, the easiest way to install pip is through the use of a python program called get-pip.py, which you can download here. When you open this link, you might be scared of the massive jumble of code that awaits you. Please don’t be. Simply use your browser to save this page under its default name, which is get-pip.py. It might be a good idea to save this file in your python directory, so you know where to find it.
Once you have saved this file, you need to run it, which can be done in two ways. If you prefer using your python interpreter, just right-click on the file get-pip.py and choose “open with” and then choose whatever python interpreter you care to use.
If you prefer to install pip using the windows command line, navigate to whatever directory you’ve placed python and get-pip.py. For this example, we’ll assume this directory is python27, so we’ll use the command C:\>cd python27. Once you are in this directory, to install pip run the command
If you want more information or help with a weird error message, check out the StackOverflow page that seems to be regularly updated.
Installing Python Modules
Now that you have pip, it is easy to install python modules since it does all the work for you. When you find a module that you want to use, usually the documentation or installation instructions will include the necessary pip command, such as
Remember, for the same reasons explained above (on Mac or Linux systems, but not Windows), you might need to run pip with sudo, like
About the author
Fred Gibbs is an assistant professor of history at the University of New Mexico.
Suggested Citation
Fred Gibbs, «Installing Python Modules with pip,» Programming Historian 2 (2013), https://doi.org/10.46430/phen0029.
Donate today!
Great Open Access tutorials cost money to produce. Join the growing number of people supporting Programming Historian so we can continue to share knowledge free of charge.
The Programming Historian (ISSN: 2397-2068) is released under a CC-BY license.
This project is administered by ProgHist Ltd, Charity Number 1195875 and Company Number 12192946.