Как установить модули в python на windows без интернета

What's the best way to download a python package and it's dependencies from pypi for offline installation on another machine? Is there any easy way to do this with pip or easy_install? I'm trying to

If the package is on PYPI, download it and its dependencies to some local directory.
E.g.

$ mkdir /pypi && cd /pypi
$ ls -la
  -rw-r--r--   1 pavel  staff   237954 Apr 19 11:31 Flask-WTF-0.6.tar.gz
  -rw-r--r--   1 pavel  staff   389741 Feb 22 17:10 Jinja2-2.6.tar.gz
  -rw-r--r--   1 pavel  staff    70305 Apr 11 00:28 MySQL-python-1.2.3.tar.gz
  -rw-r--r--   1 pavel  staff  2597214 Apr 10 18:26 SQLAlchemy-0.7.6.tar.gz
  -rw-r--r--   1 pavel  staff  1108056 Feb 22 17:10 Werkzeug-0.8.2.tar.gz
  -rw-r--r--   1 pavel  staff   488207 Apr 10 18:26 boto-2.3.0.tar.gz
  -rw-r--r--   1 pavel  staff   490192 Apr 16 12:00 flask-0.9-dev-2a6c80a.tar.gz

Some packages may have to be archived into similar looking tarballs by hand. I do it a lot when I want a more recent (less stable) version of something. Some packages aren’t on PYPI, so same applies to them.

Suppose you have a properly formed Python application in ~/src/myapp. ~/src/myapp/setup.py will have install_requires list that mentions one or more things that you have in your /pypi directory. Like so:

  install_requires=[
    'boto',
    'Flask',
    'Werkzeug',
    # and so on

If you want to be able to run your app with all the necessary dependencies while still hacking on it, you’ll do something like this:

$ cd ~/src/myapp
$ python setup.py develop --always-unzip --allow-hosts=None --find-links=/pypi

This way your app will be executed straight from your source directory. You can hack on things, and then rerun the app without rebuilding anything.

If you want to install your app and its dependencies into the current python environment, you’ll do something like this:

$ cd ~/src/myapp
$ easy_install --always-unzip --allow-hosts=None --find-links=/pypi .

In both cases, the build will fail if one or more dependencies aren’t present in /pypi directory. It won’t attempt to promiscuously install missing things from Internet.

I highly recommend to invoke setup.py develop ... and easy_install ... within an active virtual environment to avoid contaminating your global Python environment. It is (virtualenv that is) pretty much the way to go. Never install anything into global Python environment.

If the machine that you’ve built your app has same architecture as the machine on which you want to deploy it, you can simply tarball the entire virtual environment directory into which you easy_install-ed everything. Just before tarballing though, you must make the virtual environment directory relocatable (see —relocatable option). NOTE: the destination machine needs to have the same version of Python installed, and also any C-based dependencies your app may have must be preinstalled there too (e.g. say if you depend on PIL, then libpng, libjpeg, etc must be preinstalled).

Skip to content

Бывает необходимо установить пакеты для python на машине без интернета. Способов много, я выбрал для себя один, его и использую. «Легко» и «просто» можно скачать необходимые пакеты вместе с зависимостями и установить на другой машине, если сделать следующие.

На машине с интернетом

python3 -m venv vevn
source venv/bin/active
pip install pip --upgrade
# директория для скачивания пакетов
mkdir pkg
cd pkg
# отдельно скачиваю последнею версию pip
pip download pip
# скачиваю необходимые пакеты с зависимостями
pip download -r ../requirements.txt

На машине без интернета

python3 -m venv vevn
source venv/bin/active
# устанавливаю ранее скаченный pip (версия может быть другая)
pip install pkg/pip-20.1-py2.py3-none-any.whl
# установка пакетов из списка requirements.txt, пакеты должны лежать в pkg (директория)
pip install --no-index --find-links pkg -r requirements.txt

Результат выполнения

# вывод консоли у меня
pip install --no-index --find-links pkg -r requirements.txt 
Looking in links: pkg
Processing ./pkg/Flask-1.1.2-py2.py3-none-any.whl
Processing ./pkg/Flask_WTF-0.14.3-py2.py3-none-any.whl
Processing ./pkg/et_xmlfile-1.0.1.tar.gz
Processing ./pkg/openpyxl-3.0.3.tar.gz
Processing ./pkg/jdcal-1.4.1-py2.py3-none-any.whl
Processing ./pkg/pylint-2.5.2-py3-none-any.whl
Processing ./pkg/itsdangerous-1.1.0-py2.py3-none-any.whl
Processing ./pkg/Jinja2-2.11.2-py2.py3-none-any.whl
Processing ./pkg/Werkzeug-1.0.1-py2.py3-none-any.whl
Processing ./pkg/click-7.1.2-py2.py3-none-any.whl
Processing ./pkg/WTForms-2.3.1-py2.py3-none-any.whl
Processing ./pkg/mccabe-0.6.1-py2.py3-none-any.whl
Processing ./pkg/isort-4.3.21-py2.py3-none-any.whl
Processing ./pkg/toml-0.10.1-py2.py3-none-any.whl
Processing ./pkg/astroid-2.4.1-py3-none-any.whl
Processing ./pkg/MarkupSafe-1.1.1-cp37-cp37m-manylinux1_x86_64.whl
Processing ./pkg/typed_ast-1.4.1-cp37-cp37m-manylinux1_x86_64.whl
Processing ./pkg/wrapt-1.12.1.tar.gz
Processing ./pkg/lazy_object_proxy-1.4.3-cp37-cp37m-manylinux1_x86_64.whl
Processing ./pkg/six-1.14.0-py2.py3-none-any.whl
Could not build wheels for et-xmlfile, since package 'wheel' is not installed.
Could not build wheels for openpyxl, since package 'wheel' is not installed.
Could not build wheels for wrapt, since package 'wheel' is not installed.
Installing collected packages: itsdangerous, MarkupSafe, Jinja2, Werkzeug, click, Flask, WTForms, Flask-WTF, et-xmlfile, jdcal, openpyxl, mccabe, isort, toml, typed-ast, wrapt, lazy-object-proxy, six, astroid, pylint
    Running setup.py install for et-xmlfile ... done
    Running setup.py install for openpyxl ... done
    Running setup.py install for wrapt ... done
Successfully installed Flask-1.1.2 Flask-WTF-0.14.3 Jinja2-2.11.2 MarkupSafe-1.1.1 WTForms-2.3.1 Werkzeug-1.0.1 astroid-2.4.1 click-7.1.2 et-xmlfile-1.0.1 isort-4.3.21 itsdangerous-1.1.0 jdcal-1.4.1 lazy-object-proxy-1.4.3 mccabe-0.6.1 openpyxl-3.0.3 pylint-2.5.2 six-1.14.0 toml-0.10.1 typed-ast-1.4.1 wrapt-1.12.1

Мой файл requirements.txt для примера

Flask==1.1.2
Flask-WTF==0.14.3
et-xmlfile==1.0.1
openpyxl==3.0.3
jdcal==1.4.1
pylint==2.5.2

Установка из tar.gz или whl

# установка одного пакета из архива
pip install ./pkg-name.tar.gz

Offline Python Package Install Notes

Two common cases which make the install of Python packages harder due to networking issues are:
a) Install behind a Proxy
b) Install without access to the internet

(a) Install behind a Proxy

In the case where the target machine connects to the internet over a network proxy, export the following environment vars, as appropriate — http_proxy and https_proxy. Eg:

$ export https_proxy=http://proxy.mydomain.com:<port>
$ export http_proxy=http://proxy.mydomain.com:<port>
$ pip install <package>

(b) Install without access to the internet

In the case where the target machine does not have connectivity to the internet, you have to download the package and dependencies using a machine which does have connectivity to the internet. After which the install can follow. Sample instructions —

Step 1. Download Packages for Offline Install

Execute the instructions below download the packages on a machine which is able to connect to the internet.

# if a single package is being installed
$ pip install <package> --download /tmp/offline_packages

# or, if a list of dependencies are to be installed
$ pip install --download /tmp/offline_packages -r requirements.txt

Step 2. Transfer downloaded packages

Transfer downloaded packages to the target machine where the install is to be performed. Use scp/sftp/etc.

Step 3. Install packages

Assuming the directory /tmp/transferred_packages contains the contents of /tmp/offline_packages from the earlier machine, execute the following steps on the the target machine.

# if a single package is being installed
$ pip install --no-index --find-links="/tmp/tranferred_packages" <package>

# if a list of dependencies are to be installed
$ pip install --no-index --find-links="/tmp/tranferred_packages" -r requirements.txt

References

Менеджер пакетов pip: разбираемся с установкой дополнительных библиотек в Python

Smartiqa Article

Ведь не все пакеты нужны в повседневной практике или отдельном проекте, да и места они занимают не мало. Для этих целей создан удаленный репозиторий модулей https://pypi.org/ , в котором на сегодня имеется более 260 тыс. проектов на все случаи практики программирования. Вам не обязательно создавать код с нуля, так как под многие задачи уже имеется соответствующий пакет.

Работа с этим хранилищем расширений осуществляется через команду pip . Имеется и другой установщик easy_install , но он применяется существенно реже. Таким образом, пакетный менеджер pip необходим для установки, обновления, удаления и управления модулями языка Python.

2. Подготовительные мероприятия

Как видно из ответа, на данном ПК используется python версии 3.8 и pip версии 20.2.3 .

В некоторых случаях (актуально для пользователей Linux или macOS ) требуется применять команду pip3 (если в результате выполнения pip определяет, что у вас установлен python версии 2 по умолчанию). Это связано с тем, что на *nix системах присутствуют сразу обе версии языка.

Также если на вашем компьютере имеется несколько версий языка Python (например, 3.6 , 3.8 , 3.9 ), то менеджер пакетов может применяться отдельно для каждой из них:

3. Установка и удаление пакетов

При разработке сложных проектов может понадобиться установка большого количества модулей. Постоянно их скачивать из репозитория PyPi трудоемко. Для этого разработан способ загрузки пакетов локально. Они могут находиться в архивах ( *.tar.gz ) или специальных файлах с расширением .whl . Это удобно и в том случае, если нет доступа в интернет у выбранной машины, и вы заранее создали пакет со всеми необходимыми библиотеками.

Для примера запакуем модуль numpy в «колесо» ( wheel ) и установим его оттуда.

Вначале мы создали специальный локальный пакет NumPy и поместили его в текущую папку (о чем свидетельствует точка). В директории создался файл numpy-1.19.2-cp38-cp38-win32.whl . На его основании даже без интернета мы легко сможем установить данную библиотеку. Команда «—no-index» говорит о том, чтобы мы не искали модуль в репозитории PyPi , а —find-links принудительно указывает место расположения пакета. Когда речь идет о сотне пакетов, это очень удобно. Правда для этого необходимо освоить еще один инструмент: набор зависимостей (о нем – следующий раздел).

Рассмотрим вопрос удаления модулей. Если требуется удалить один пакет, то делается это по аналогии с установкой:

Читайте также

4. Файлы требований для управления пакетами

Серьезные и многоуровневые приложения никогда не обходятся одной библиотекой. Даже когда вы устанавливали тот же NumPy , вы могли заметить, что помимо самого модуля скачивались дополнительные пакеты, которые мы не запрашивали. Естественно они необходимы для правильной работы NumPy . Но откуда известно, что они нужны?

Как установить модули python без интернета и pip?

kgb_zor

Kostyan4ik, почему это нет возможности? С питоном всегда можно найти какую-нибудь возможность.

Вот, к примеру, вы можете на том компе, где есть питон и интернет, скачать все необходимые пакеты с помощью того же pip:
pip download pip
Так вы можете скачать все необходимые пакеты и принести их на машину без инета просто на флешке.
А там:

Тут происходит маленькая магия: вы с помощью питона запускаете pip прямо изнутри локально лежащего файла с его дистрибутивом. Этим pip’ом вы ставите самого себя на локальную машину. Примерно как Барон Мюнхаузен, но не больно.

Вы также можете сохранить перечень всех установленных пакетов на компе с инетом в текстовый файл, а потом, убрав из него лишнее, скачать все эти пакеты в локальный каталог, отнести на оффлайн-комп и там ставить через тот же pip

Лучший ответСообщение было отмечено wourld как решение

Установка Unity3D без интернета
Нужно автономно без подключения к интернету установить Unity3d. Скажем, с флешки , это реально?

I have recently started studying Python, using a combination of Automate the Boring Stuff by Al Sweigart and Python Programming, an Introduction Into Computer Science by John M. Zelle, if I want a deeper look. I intend to find some more complete books once I’ve worked through these.

I have however stumbled into a problem. Automate the Boring Stuff explains how to add modules to python using the pip tool.

I however live in rural Tennessee, where they charge $150 per month for a 1.5 mbs DSL connection (can you tell I’m a bit salty?)

This means that my only Internet connection is the mobile data on my cellphone, and that only outside the house…

Can anyone give me instructions directed towards a novice on how I might be able to download the modules using my phone, and after transferring them to the PC, what commands I should run to add them to python? Any explanations of how and why it works that way is highly appreciated as well. It is a learning experience, after all.

Thanks for your help.

I have recently started studying Python, using a combination of Automate the Boring Stuff by Al Sweigart and Python Programming, an Introduction Into Computer Science by John M. Zelle, if I want a deeper look. I intend to find some more complete books once I’ve worked through these.

I have however stumbled into a problem. Automate the Boring Stuff explains how to add modules to python using the pip tool.

I however live in rural Tennessee, where they charge $150 per month for a 1.5 mbs DSL connection (can you tell I’m a bit salty?)

This means that my only Internet connection is the mobile data on my cellphone, and that only outside the house…

Can anyone give me instructions directed towards a novice on how I might be able to download the modules using my phone, and after transferring them to the PC, what commands I should run to add them to python? Any explanations of how and why it works that way is highly appreciated as well. It is a learning experience, after all.

Thanks for your help.

Installing a python module or package (any applications) is very easy if you have internet connection and access to public repo or private repo.

Eg:

$ pip install pywinrm

But what if your production server do not have internet access and your repo server do not have this package to be installed ?

Here is the simple scenario; I am automating Window machines using Ansible. For Windows modules to work I need pywinrm module to be installed on the Ansible machine and I do not have internet access on Ansible.

Refer all Ansible Learning Guides here.

If the module or library do not have dependancies, then you simply download the package pypi.org/project/pywinrm and transfer this Ansible machine (or the machine which do not have internet access). But in our case, the pywinrm module have dependancies and we do not know what are the dependancies to be installed.

There is an easy method we can follow in this situation.

Download the package from connected machine

Create a directory as repository to keep the packages and dependancies.

[email protected] $ mkdir pywinrm-local

From a machine which is connected to internet, download the packages and dependancies using pip download command. (We will download the package and dependancies to a directory to avoid mix-up)

[email protected] $ pip download pywinrm -d pywinrm-local 
Collecting pywinrm
  Using cached pywinrm-0.4.2-py2.py3-none-any.whl (44 kB)
Collecting requests>=2.9.1
  Using cached requests-2.26.0-py2.py3-none-any.whl (62 kB)
Collecting requests-ntlm>=0.3.0
  Using cached requests_ntlm-1.1.0-py2.py3-none-any.whl (5.7 kB)
Collecting xmltodict
  Using cached xmltodict-0.12.0-py2.py3-none-any.whl (9.2 kB)
Collecting six
  Using cached six-1.16.0-py2.py3-none-any.whl (11 kB)
Collecting charset-normalizer~=2.0.0
  Using cached charset_normalizer-2.0.9-py3-none-any.whl (39 kB)
Collecting urllib3<1.27,>=1.21.1
  Using cached urllib3-1.26.7-py2.py3-none-any.whl (138 kB)
Collecting idna<4,>=2.5
  Using cached idna-3.3-py3-none-any.whl (61 kB)
Collecting certifi>=2017.4.17
  Using cached certifi-2021.10.8-py2.py3-none-any.whl (149 kB)
Collecting ntlm-auth>=1.0.2
  Using cached ntlm_auth-1.5.0-py2.py3-none-any.whl (29 kB)
Collecting cryptography>=1.3
  Using cached cryptography-36.0.1-cp36-abi3-macosx_10_10_x86_64.whl (2.6 MB)
Collecting cffi>=1.12
  Using cached cffi-1.15.0-cp39-cp39-macosx_10_9_x86_64.whl (178 kB)
Collecting pycparser
  Using cached pycparser-2.21-py2.py3-none-any.whl (118 kB)
Saved ./pywinrm-local/pywinrm-0.4.2-py2.py3-none-any.whl
Saved ./pywinrm-local/requests-2.26.0-py2.py3-none-any.whl
Saved ./pywinrm-local/requests_ntlm-1.1.0-py2.py3-none-any.whl
Saved ./pywinrm-local/six-1.16.0-py2.py3-none-any.whl
Saved ./pywinrm-local/xmltodict-0.12.0-py2.py3-none-any.whl
Saved ./pywinrm-local/certifi-2021.10.8-py2.py3-none-any.whl
Saved ./pywinrm-local/charset_normalizer-2.0.9-py3-none-any.whl
Saved ./pywinrm-local/cryptography-36.0.1-cp36-abi3-macosx_10_10_x86_64.whl
Saved ./pywinrm-local/idna-3.3-py3-none-any.whl
Saved ./pywinrm-local/ntlm_auth-1.5.0-py2.py3-none-any.whl
Saved ./pywinrm-local/urllib3-1.26.7-py2.py3-none-any.whl
Saved ./pywinrm-local/cffi-1.15.0-cp39-cp39-macosx_10_9_x86_64.whl
Saved ./pywinrm-local/pycparser-2.21-py2.py3-none-any.whl
Successfully downloaded pywinrm requests requests-ntlm six xmltodict certifi charset-normalizer cryptography idna ntlm-auth urllib3 cffi pycparser

Now transfer the directory and content to target machine (disconnected machine) – the Ansible controlnode in our scenario – using any of the available methods. (scp, sftp, winscp etc)

[email protected] $ scp -rp pywinrm-local [email protected]:/home/user/pywinrm-local

Install package on the disconnected machine

Verify the transferred packages and dependancy file; you will see all the .whl files inside.

[email protected] $ ls -l pywinrm-local 
total 6696
-rw-r--r--  1 user  user   149195  3 Jan 15:14 certifi-2021.10.8-py2.py3-none-any.whl
-rw-r--r--  1 user  user   178951  3 Jan 15:14 cffi-1.15.0-cp39-cp39-macosx_10_9_x86_64.whl
-rw-r--r--  1 user  user    39257  3 Jan 15:14 charset_normalizer-2.0.9-py3-none-any.whl
-rw-r--r--  1 user  user  2558077  3 Jan 15:14 cryptography-36.0.1-cp36-abi3-macosx_10_10_x86_64.whl
-rw-r--r--  1 user  user    61160  3 Jan 15:14 idna-3.3-py3-none-any.whl
-rw-r--r--  1 user  user    29980  3 Jan 15:14 ntlm_auth-1.5.0-py2.py3-none-any.whl
-rw-r--r--  1 user  user   118697  3 Jan 15:14 pycparser-2.21-py2.py3-none-any.whl
-rw-r--r--  1 user  user    44274  3 Jan 15:14 pywinrm-0.4.2-py2.py3-none-any.whl
-rw-r--r--  1 user  user    62251  3 Jan 15:14 requests-2.26.0-py2.py3-none-any.whl
-rw-r--r--  1 user  user     5717  3 Jan 15:14 requests_ntlm-1.1.0-py2.py3-none-any.whl
-rw-r--r--  1 user  user    11053  3 Jan 15:14 six-1.16.0-py2.py3-none-any.whl
-rw-r--r--  1 user  user   138764  3 Jan 15:14 urllib3-1.26.7-py2.py3-none-any.whl
-rw-r--r--  1 user  user     9170  3 Jan 15:14 xmltodict-0.12.0-py2.py3-none-any.whl

Create a requirements.txt file with all filenames in the repo directory (eg: pywinrm-local)

[email protected] $ ls -l pywinrm-local |awk '{print $9}' > pywinrm-local/requirements.txt

Now Install the package using pip command by specifying the source repo directory.

[email protected] $ pip install 
  -r pywinrm-local/requirements.txt 
  --find-links=pywinrm-local 
  --no-index

Verify installed Python module

[email protected] $ pip list |grep pywinrm
pywinrm            0.4.2

You can use this method for any complex python deployments but just need to make sure all the dependancies are downloaded to the same repo directory.

Disclaimer: The views expressed and the content shared are those of the author and do not reflect the views of the author’s employer or techbeatly platform.

Понравилась статья? Поделить с друзьями:
  • Как установить на чистый комп windows 10
  • Как установить модем мегафон на ноутбук windows 10
  • Как установить на флешку windows server 2003
  • Как установить модем йота на ноутбук windows 10
  • Как установить на флешку windows 7 видео