A Quick Note : Installing Python Wheels Programmatically

A Quick Note: Installing Python Wheels Programmatically

If for whatever reason you wish to install Python wheels using a Python script you can do so as described below.

First of all, one needs to determine which wheel to choose in accordance with the platform, Python implementation, etc. Here is an example.

Figuring out python which Python implementation you have installed:

Python Implementation
1
2
3
4
>>> import platform
>>> platform.python_implementation()
'CPython'
>>>

Determining whether your Python binaries are 32 or 64-bit:

Python Binaries Architecture
1
2
3
>>> import struct
>>> 8 * struct.calcsize("P")
64

And here is how you can find out the operating system under which the script is executed:

Operating System
1
2
3
4
5
>>> import platform
>>> platform.system()
'Linux'
>>> platform.machine()
'x86_64'

The requirements are encoded into the file name of a wheel. For example: “torch-1.1.0-cp35-cp35m-linux_x86_64.whl” is a PyTorch wheel for CPython 3.5 run on 64-bit Linux platform. A more detailed explanation is to be found in Brett Cannon’s excellent blog post.

Having identified the wheel, installing it is a simple matter. It is advisable to begin by upgrading pip to the latest version.

Upgrading Pip
1
python3.5 -m pip install --upgrade pip

Finally, run the following script passing it a path to a predownloaded wheel file as a parameter:

Installing a Wheel
1
2
3
4
5
6
7
import pip._internal as p

w = p.wheel.Wheel(sys.argv[1])
if not w.supported():
	print(p.pep425tags.get_supported())
else:
	p.main(['install', sys.argv[1]])

Using these simple code snippets, one can easily put together an installation script tailored to the task one is faced with.

– Ry Auscitte

References

Brett Cannon, The challenges in designing a library for PEP 425 (aka wheel tags), 2019