Use pip install in python script

I need to install a package from PyPi straight within my script. Maybe there's some module or distutils (distribute, pip etc.) feature which allows me to just execute something like pypi.install('requests') and requests will be installed into my virtualenv.

asked Sep 8, 2012 at 17:33

chuwychuwy

5,9084 gold badges19 silver badges27 bronze badges

10

The officially recommended way to install packages from a script is by calling pip's command-line interface via a subprocess. Most other answers presented here are not supported by pip. Furthermore since pip v10, all code has been moved to pip._internal precisely in order to make it clear to users that programmatic use of pip is not allowed.

Use sys.executable to ensure that you will call the same pip associated with the current runtime.

import subprocess
import sys

def install(package):
    subprocess.check_call([sys.executable, "-m", "pip", "install", package])

Use pip install in python script

wim

311k94 gold badges569 silver badges708 bronze badges

answered May 9, 2018 at 13:47

Aaron de WindtAaron de Windt

15.8k12 gold badges45 silver badges61 bronze badges

7

You can also use something like:

import pip

def install(package):
    if hasattr(pip, 'main'):
        pip.main(['install', package])
    else:
        pip._internal.main(['install', package])

# Example
if __name__ == '__main__':
    install('argh')

answered Apr 11, 2013 at 13:54

Rikard AnglerudRikard Anglerud

4,5492 gold badges15 silver badges3 bronze badges

23

If you want to use pip to install required package and import it after installation, you can use this code:

def install_and_import(package):
    import importlib
    try:
        importlib.import_module(package)
    except ImportError:
        import pip
        pip.main(['install', package])
    finally:
        globals()[package] = importlib.import_module(package)


install_and_import('transliterate')

If you installed a package as a user you can encounter the problem that you cannot just import the package. See How to refresh sys.path? for additional information.

answered Jul 16, 2014 at 6:45

rominfrominf

2,4513 gold badges19 silver badges37 bronze badges

6

This should work:

import subprocess

def install(name):
    subprocess.call(['pip', 'install', name])

answered Sep 8, 2012 at 17:52

Use pip install in python script

quantumquantum

3,52028 silver badges50 bronze badges

11

i added some exception handling to @Aaron's answer.

import subprocess
import sys

try:
    import pandas as pd
except ImportError:
    subprocess.check_call([sys.executable, "-m", "pip", "install", 'pandas'])
finally:
    import pandas as pd

answered Sep 21, 2019 at 12:58

Use pip install in python script

Sohan DasSohan Das

1,4402 gold badges14 silver badges16 bronze badges

4

For installing multiple packages, I am using a setup.py file with the following code:

import sys
import subprocess
import pkg_resources

required  = {'numpy', 'pandas', ''} 
installed = {pkg.key for pkg in pkg_resources.working_set}
missing   = required - installed

if missing:
    # implement pip as a subprocess:
    subprocess.check_call([sys.executable, '-m', 'pip', 'install', *missing])

Use pip install in python script

answered Jul 26, 2020 at 6:09

1

import os
os.system('pip install requests')

I tried above for temporary solution instead of changing docker file. Hope these might be useful to some

answered Nov 30, 2020 at 15:20

Use pip install in python script

1

You define the dependent module inside the setup.py of your own package with the "install_requires" option.

If your package needs to have some console script generated then you can use the "console_scripts" entry point in order to generate a wrapper script that will be placed within the 'bin' folder (e.g. of your virtualenv environment).

answered Sep 8, 2012 at 17:38

3

If you want a more efficient answer that expands on subprocess.check_call. You can first check if the requirement has already been met using pkg_resources.

This works for different requirment specifiers which is nice. e.g. >=, ==

import sys
import subprocess
import pkg_resources
from pkg_resources import DistributionNotFound, VersionConflict

def should_install_requirement(requirement):
    should_install = False
    try:
        pkg_resources.require(requirement)
    except (DistributionNotFound, VersionConflict):
        should_install = True
    return should_install


def install_packages(requirement_list):
    try:
        requirements = [
            requirement
            for requirement in requirement_list
            if should_install_requirement(requirement)
        ]
        if len(requirements) > 0:
            subprocess.check_call([sys.executable, "-m", "pip", "install", *requirements])
        else:
            print("Requirements already satisfied.")

    except Exception as e:
        print(e)

Example usage:

requirement_list = ['requests', 'httpx==0.18.2']
install_packages(requirement_list)

Use pip install in python script

Relevant Info Stackoverflow Question: 58612272

answered Aug 8, 2021 at 16:45

Use pip install in python script

Glen ThompsonGlen Thompson

8,0074 gold badges49 silver badges48 bronze badges

1

Try the below. So far the best that worked for me Install the 4 ones first and then Mention the new ones in the REQUIRED list

import pkg_resources
import subprocess
import sys
import os

REQUIRED = {
  'spacy', 'scikit-learn', 'numpy', 'pandas', 'torch', 
  'pyfunctional', 'textblob', 'seaborn', 'matplotlib'
}

installed = {pkg.key for pkg in pkg_resources.working_set}
missing = REQUIRED - installed

if missing:
    python = sys.executable
    subprocess.check_call([python, '-m', 'pip', 'install', *missing], stdout=subprocess.DEVNULL)

answered May 2, 2021 at 19:59

RijinRijin

858 bronze badges

1

To conditionally install multiple packages with exact version, I've been using this pattern basing on @Tanmay Shrivastava's answer:

import sys
from subprocess import run, PIPE, STDOUT
import pkg_resources

def run_cmd(cmd):
    ps = run(cmd, stdout=PIPE, stderr=STDOUT, shell=True, text=True)
    print(ps.stdout)


# packages to be conditionally installed with exact version
required = {"click==8.0.1", "semver==3.0.0.dev2"}
installed = {f"{pkg.key}=={pkg.version}" for pkg in pkg_resources.working_set}
missing = required - installed

if missing:
    run_cmd(f'pip install --ignore-installed {" ".join([*missing])}')

answered Sep 21, 2021 at 16:29

Use pip install in python script

Glenn MohammadGlenn Mohammad

3,0304 gold badges31 silver badges42 bronze badges

Can I use pip install in Python script?

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.

How do I install Python pip code?

How To Install PIP to Manage Python Packages On Windows.
Step 1: Download PIP get-pip.py..
Step 2: Installing PIP on Windows..
Step 3: Verify Installation..
Step 4: Add Pip to Windows Environment Variables..
Step 5: Configuration..

Why is pip install not working in Python?

One of the most common problems with running Python tools like pip is the “not on PATH” error. This means that Python cannot find the tool you're trying to run in your current directory. In most cases, you'll need to navigate to the directory in which the tool is installed before you can run the command to launch it.

How do I know if pip is installed in Python?

To check if PIP is already installed on Windows, we should open the command line again, type pip , and press Enter . If PIP is installed, we will receive a long notification explaining the program usage, all the available commands and options.