“pip” module Usage: PyPI Package Manager

Usage of “pip” module: PyPI Package Manager is helpful when you may need to use pip package manager inside python eg. when some imports may raise.

ImportError and you want to handle the exception. If you unpack on Windows

Python_root/Scripts/pip.exeinside is stored main.py file, where main class from pip package is imported.

This means pip package is used whenever you use pip executable. For usage of pip as executable see: pip: PyPI

Package Manager

Example use of commands

import pip
command = 'install'
parameter = 'selenium'
second_param = 'numpy' # You can give as many package names as needed switch = '--upgrade'
pip.main([command, parameter, second_param, switch])

Only needed parameters are obligatory, so both pip.main([‘freeze’]) and pip.main([‘freeze’, ”, ”]) are acceptable.

Batch install

It is possible to pass many package names in one call, but if one install/upgrade fails, whole installation process stops and ends with status ‘1’.

import pip
installed = pip.get_installed_distributions()
list = []
for i in installed:

If you don’t want to stop when some installs fail, call installation in loop.

for i in installed:

“pip” module: Handling ImportError Exception

When you use python file as module there is no need always check if package is installed but it is still useful for scripts.

if name == 'main':
import requests
except ImportError:
print("To use this module you need 'requests' module")
t = input('Install requests? y/n: ')
if t == 'y':
import pip
pip.main(['install', 'requests'])
import requests
import os
import sys
import os
import sys
print('Some functionality can be unavailable.')
import requests
import os
import sys

“pip” module: Force install

Many packages for example on version 3.4 would run on 3.6 just fine, but if there are no distributions for specific

platform, they can’t be installed, but there is workaround. In .whl files (known as wheels) naming convention decide

whether you can install package on specified platform. Eg.

scikit_learn‑0.18.1‑cp36‑cp36m‑win_amd64.whl[package_name]-[version]-[python interpreter]-[python-
interpreter]-[Operating System].whl. If name of wheel file is changed, so platform does match, pip tries to install

package even if platform or python version does not match. Removing platform or interpreter from name will rise

an error in newest version of pip module kjhfkjdf.whl is not a valid wheel filename..

Alternatively .whl file can be unpacked using an archiver as 7-zip. – It usually contains distribution meta folder and folder with source files. These source files can be simply unpacked to site-packages directory unless this wheel contain installation script, if so, it has to be run first.

Learn More


Please enter your comment!
Please enter your name here