how to install python packages using script

How to Install Python Package Using Script

Sometimes you may need to automate installation of python packages. You can do by installing python package with the help of a script. We will learn how to execute pip package manager using subprocess in python. pip command is the package manager used to install most, if not all, python packages. Typically, it is run on terminal or command prompt. But if you need to run it within python script, you need to use subprocess function which allows you to run terminal commands from within python script.

How to Install Python Package Using Script

Please note, although we are describing steps to execute pip command from within python script, it is not supported by Python Package Authority (PyPA) because it is not thread-safe, and is meant to be run as a single process.

Nevertheless, here is a simple function to run pip as a subprocess. Replace <packagename> with the name of package that you want to install.

import sys
import subprocess

# implement pip as a subprocess:
subprocess.check_call([sys.executable, '-m', 'pip', 'install', 

The above commands will install the package as well as its dependencies. In the above code, we import sys and subprocess modules. We call check_call() function to execute the pip command from within python script.

If you are using Anaconda Python version, then you can call conda command from within subprocess, as shown below. Replace <packagename> with name of package.

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

# implement conda as a subprocess:

subprocess.check_call([sys.executable, '-m', 'conda', 'install', 

In this article, we have learnt a couple of ways to install python package using script. Basically, we need to use subprocess to run the pip/conda command which we would have otherwise run in terminal/command prompt.

Also read:

How to Iterate Over List in Chunks
How to Create Python Dictionary from Strings
How to Strip HTML from String in JavaScript
How to Preload Images with jQuery
How to Make Python Dictionary from Two Lists

Leave a Reply

Your email address will not be published.