How to Install Python Packages using a Script

How to Install Python Packages Using a Script

In some cases, you may need to automate the updating of multiple Python deployments with a specific package or set of packages. This resource provides examples of how to create a Python script that runs pip (the recommended package manager) or conda as a subprocess in order to install Python packages.

Warning:

Use of a Python script to run pip to install a package is not supported by the Python Packaging Authority (PyPA) for the following reason:

  • Pip is not thread-safe, and is intended to be run as a single process. When run as a thread from within a Python script, pip may affect non-pip code with unexpected results.

However, PyPA fully supports using a Python script to run pip as a subprocess. 

Python Installation Checklist

Before packages can be installed, ensure that a Python installation containing the necessary files needed for installing  packages is in place by following the Installation Requirements.

How to Run Pip as a SubProcess

When it comes to automating the installation of Python packages, you can create a Python script that runs pip as a subprocess with just a few lines of code:

import sys
import subprocess

# implement pip as a subprocess:
subprocess.check_call([sys.executable, '-m', 'pip', 'install', 
'<packagename>'])

The package, as well as any requirements will be installed. 

  • Note: pip installs wheels by default. Wheels include package requirements. If pip does not find a wheel to install, it will build one.

Interactive Usage

If you’re running the script interactively, it’s good practice to confirm the installation. The following script will run pip as a subprocess to install one or more packages, and then print an updated list of installed packages:

import sys
import subprocess

# implement pip as a subprocess:
subprocess.check_call([sys.executable, '-m', 'pip', 'install',
'<packagename>'])

# process output with an API in the subprocess module:
reqs = subprocess.check_output([sys.executable, '-m', 'pip',
'freeze'])
installed_packages = [r.decode().split('==')[0] for r in reqs.split()]

print(installed_packages)

How to run Conda as a SubProcess

If you’re working with Anaconda’s version of Python, you can also run Anaconda’s package manager (conda) as a subprocess in order to install Python packages. The following Python script provides an example:

import sys
import subprocess
import conda.cli.python_api as Conda

# implement conda as a subprocess:

subprocess.check_call([sys.executable, '-m', 'conda', 'install', 
'<packagename>'])

The specified package(s), along with any requirements will be installed and displayed as output.

Try a faster way of installing Python packages for Windows. Get ActivePython or build your own Python runtime with the packages you need. Get started free on the ActiveState Platform.

Related Quick Reads:

How to Manually Install Python Packages

Python Packages

Katie Chang