- Установка python setuptools easy_install и работа с ним
- Как установить библиотеку в Python: руководство для новичка
- Ручная установка
- 1. Установите setuptools.
- 2. Откройте сессию терминала
- 3. Запустите команду:
- 4. Внимание!
- Установка с помощью easy install
- Установка pip
- Заключение
- Python-разработчик
- Getting Started With setuptools and setup.py В¶
- Installing setuptools and easy install¶
- Bootstrapping setuptools¶
- Setting up setup.py В¶
- Directory Structure¶
- README¶
- Classifiers¶
- Using setup.py В¶
- Intermezzo: .pypirc file and gpg¶
- Registering Your Project¶
- Uploading Your Project¶
- Putting It All Together With The Full Windows Script¶
- Installing SetupTools on 64-bit Windows
- 11 Answers 11
- How do I set up Setuptools for Python 2.6 on Windows?
- 14 Answers 14
Установка python setuptools easy_install и работа с ним
setuptools дополнение для python на данный момент до версии 2.7 позволяющее автоматически загружать и устанавливать пакеты одной строчкой из коммандной строки или консоли для никс систем.
В состав пакета setuptools входит модуль easy_install который позволяет выполнять такие действия как автоматическая загрузка пакетов и их установка, обновление, откат до предыдущей версии.
Для использования easy_install необходимо скачать setuptools и установить, так как автоматика еще не установлена, то все делаем вручную, точнее вручную скачиваем инсталятор ставящий пакет (рассматриваем установку под виндовс)
Обращаю внимание, что setuptools как и easy_install.py доступно на текущий только для python до версии 2.7
Для загрузки переходим на страницу http://pypi.python.org/pypi/setuptools
Пролистав в самый низ странички видим таблицу с доступными пакетами для загрузки, если у нас стоит виндовс и питон 2.7, то выбираем нижний пакет с названием setuptools-0.6c11.win32-py2.7.exe
Загружаем, запускаем инсталятор, производим установку setooptools, после установки переходим в каталог в который установлен питон:
/Python27/Scripts/ и видим там easy_install.exe который запускается из коммандной строки
Теперь чтобы установить пакет достаточно набрать в коммандной строке
easy_install pyside
и будет установлена бесплатная библиотека для работы с графическим интерфейсом QT4
Примечание: если easy_install не запускается из коммандной строки, то необходимо дописать путь по которому искать приложение в переменные среды (для XP — свойства системы — вкладка дополнительно — кнопка внизу переменные среды — группа Системные переменные — Path — изменить и путь до папки Scripts — применить изменения).
Дополнительные источники информации:
1) Примеры работы с Easy Install
Как установить библиотеку в Python: руководство для новичка
Знания расширяют сознание, а библиотеки — возможности языков программирования. Расскажем, как подключить их в Python.
Мы уже рассказывали, как установить Python на различные операционные системы. Если хотите расширить возможности языка, используйте менеджер пакетов — именно с ним подключают библиотеки и модули. А если стоит вопрос, как научиться программировать на Python и получить работу, записывайтесь на курс «Python-разработчик».
Ручная установка
В этом способе не нужен традиционный установщик пакетов pip — модуль подключается прямо из источника. Это удобно, когда у вас несколько версий Python и нужно импортировать модуль в разные. Рекомендуем научиться делать это сразу.
Автор в сфере IT, digital, экономики и финансов. Ведет некоммерческий проект для начинающих писателей «ЛитЦех».
1. Установите setuptools.
Для этого скачайте файл с PyPI и извлеките его в системе.
2. Откройте сессию терминала
Поменяйте каталог на папку с файлом setup.
3. Запустите команду:
4. Внимание!
Если Python расположен вне пути вашей системы, она выдаст ошибку, что команда не найдена. Тогда укажите путь вручную. Для Windows это выглядит так:
Установка с помощью easy install
Название говорит само за себя — способ легкий, буквально в два клика. Если устанавливали вручную, то на компьютере уже стоит setuptools, и вы сможете использовать easy install, что лежит в папке со скриптами Python.
Если добавить папку со скриптами в путь операционной системы, вы сможете вызвать easy install через командную строку без указания полного адреса.
Теперь выполните следующее:
И автоматически установите любой необходимый пакет. Однако есть ограничения:
- Он может попробовать запустить пакет, который еще не загрузился до конца.
- С помощью easy install нельзя провести деинсталляцию.
Из-за этих и других причин в сообществе языка Python придумали и реализовали программу pip.
Установка pip
Она появилась в Python 3.4 и скачивается вместе с самим языком, но если у вас более ранняя версия, то установите pip вручную:
- Зайдите в PyPI и скачайте скрипт get-pip.py.
- Затем выполните команду:
Установятся setuptools, если ранее его не было на компьютере, и сам pip. С его помощью подключают любые библиотеки и файлы — всё, что только может установить easy install. Но теперь для этого будет использоваться иная команда:
А для обновления пакета применяйте:
Заключение
Мы рассказали, как подключить библиотеку в «Питоне» несколькими способами. Как видите, ничего сложного нет, если вооружиться правильными гайдами. А если нужна помощь или мотивация для изучения языка, то попробуйте курс «Python-разработчик», где за короткий период вы вооружитесь всеми необходимыми знаниями и навыками.
Python-разработчик
Практический четырёхмесячный курс для тех, кто хочет научиться основам программирования на универсальном, понятном и лаконичном языке с индивидуальным наставником, а также создать свою первую программу на Python и получить реальный опыт разработки.
Getting Started With setuptools and setup.py В¶
setuptools is a rich and complex program. This tutorial will focus on the bare minimum basics you need to get setuptools running so you can:
- Register your package on pypi.
- Build egg, source, and window installer ‘distributables’.
- Upload these ‘distributables’ to pypi.
Installing setuptools and easy install¶
To install setuptools visit http://pypi.python.org/pypi/setuptools and follow the instructions for your operating system. Also, check out http://peak.telecommunity.com/DevCenter/EasyInstall for more instructions on how to install setup tools.
Currently (as of November, 2009), setuptools is pretty easy to install for Python version 2.3 through 2.6.
Bootstrapping setuptools¶
If you are having trouble setting up setuptools for your platform, you may want to check out the ‘bootstrap’ setuptools script at http://peak.telecommunity.com/dist/ez_setup.py.
You can run this like this:
and it will install setuptools for whichever version of Python python refers to. For example on windows:
will install a setuptools for your python24 distribution.
Setting up setup.py В¶
All the features of what can go into a setup.py file is beyond the scope of this simple tutorial. I’ll just focus on a very basic and common format needed to get this project onto pypi.
The contents of setup.py is just pure python:
Directory Structure¶
The directory structure, so far, should look like this:
README¶
A nice idea stolen from http://pypi.python.org/pypi/Sphinx-PyPI-upload is to include a README text file which your code. This would be visible when someone, say, cloned your repo.
Using the simple read function, it is easy to include this in the long_description keyword arg for the setuptools.setup() function.
Classifiers¶
A really nice website is http://pypi.python.org/pypi?%3Aaction=list_classifiers which lists all the classifiers you can use in the setup call.
A sample of this website is:
Using setup.py В¶
The basic usage of setup.py is:
To see all commands type:
And you will get:
Intermezzo: .pypirc file and gpg¶
In order to interact with pypi, you first need to setup an account. Go to http://pypi.python.org/pypi and click on Register .
Now, once registered, when you run setup.py commands that interact with pypi you’ll have to enter your username and password each time.
To get around this, place a .pypirc file in your $HOME directory on linux. On windows, an you’ll need to set a HOME environ var to point to the directory where this file lives.
The structure of a .pypirc file is pretty simple:
There’s probably away around having your plain text password in this file, but I don’t know of the solution and haven’t looked into it.
Also, you often want to sign the files using gpg encryption. Visit http://www.gnupg.org/ on linux or http://www.gpg4win.org/ on windows to install this software.
Registering Your Project¶
With your setup.py and .pypirc in place, registering your project is pretty simple. Just type:
I would say more, but it is just that simple.
Uploading Your Project¶
There are three major setup.py commands we will use:
- bdist_egg : This creates an egg file. This is what is necessary so someone can use easy_install your_project .
- bdist_wininst : This will create an .exe that will install your project on a windows machine.
- sdist : This create a raw source distribution which someone can download and run python setup.py directly.
A key point here is you need to run these commands with the version of python you want to support. We’ll cover this in the Putting It All Together With The Full Windows Script below.
You can run these commands by themselves and simply create the files but not upload them. However, for this project, we always marry these commands with the upload directive which will both build and upload the necessary files.
Putting It All Together With The Full Windows Script¶
This project was build on a windows machine. To best understand how it all works and the other options used when using setup.py let’s just look at the .bat file I use to build the package and upload it to pypi:
For linux, it would be pretty much the same commands, just changing around the directories to point to the correct python versions.
I use the set HOME=C:\Users\Owner\ instead of setting an environ variable on windows
Installing SetupTools on 64-bit Windows
I’m running Python 2.7 on Windows 7 64-bit, and when I run the installer for setuptools it tells me that Python 2.7 is not installed. The specific error message is:
My installed version of Python is:
I’m looking at the setuptools site and it doesn’t mention any installers for 64-bit Windows. Have I missed something or do I have to install this from source?
11 Answers 11
Apparently (having faced related 64- and 32-bit issues on OS X) there is a bug in the Windows installer. I stumbled across this workaround, which might help — basically, you create your own registry value HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.6\InstallPath and copy over the InstallPath value from HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\InstallPath . See the answer below for more details.
If you do this, beware that setuptools may only install 32-bit libraries.
NOTE: the responses below offer more detail, so please read them too.
Problem: you have 64-bit Python, and a 32-bit installer. This will cause problems for extension modules.
The reasons why the installer doesn’t finds Python is the transparent 32-bit emulation from Windows 7. 64-bit and 32-bit programs will write to different parts of the Windows registry.
This means that the 64-bit Python installer writes to HKLM\SOFTWARE\Python , but the 32-bit setuptools installer looks at HKLM\SOFTWARE\wow6432node\Python (this is handled by windows automatically, programs don’t notice). This is expected behavior and not a bug.
Usually, you have these choices:
- the «clean» way: use 32-bit Python if you have to use 32-bit modules or extensions
- the other «clean» way: only use 64-bit installers when using 64-bit Python (see below)
- what the answer above suggests: copy HKLM\SOFTWARE\Python to HKLM\SOFTWARE\wow6432node\Python , but this will cause problems with binary distributions, as 64-bit Python can’t load 32-bit compiled modules (do NOT do this!)
- install pure Python modules with setuptools instead of the distutils installer (easy_install or pip)
For setuptools itself, for example, you can’t use a 32-bit installer for 64-bit Python as it includes binary files. But there’s a 64-bit installer at http://www.lfd.uci.edu/
gohlke/pythonlibs/ (has many installers for other modules too). Nowadays, many packages on PyPi have binary distributions, so you can install them via pip.
How do I set up Setuptools for Python 2.6 on Windows?
Is there any way to install Setuptools for Python 2.6 in Windows without having an exe installer?
There isn’t one built at the moment, and the maintainer of Setuptools has stated that it will probably be a while before he’ll get to it.
Does anyone know of a way to install it anyway?
14 Answers 14
First Option — Online Installation (i.e. remaining connected to the Internet during the entire installation process):
- Download setuptools-0.6c9.tar.gz
- Use 7-zip to extract it to a folder(directory) outside your Windows Python installation folder
- Go the folder (refer step 2) and run ez_setup.py from the corresponding dos (command) prompt
- Ensure that your PATH includes the appropriate C:\Python2X\Scripts directory
- Download setuptools-0.6c9.tar.gz
- Download setuptools-0.6c9-py2.6.egg to a folder(directory) outside your Windows Python installation folder
- Use 7-zip to extract ez_setup.py in the same folder as setuptools-0.6c9-py2.6.egg
- Go to the corresponding dos prompt and run python ez_setup.py setuptools-0.6c9-py2.6.egg from the command prompt
- Ensure that your PATH includes the appropriate C:\Python2X\Scripts directory
Third Option (assuming that you have Visual Studio 2005 or MinGW on your machine)