Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Installing python module within code

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.

like image 644
chuwy Avatar asked Sep 08 '12 17:09

chuwy


People also ask

How do I install Python modules inside?

You can install modules or packages with the Python package manager (pip). To install a module system wide, open a terminal and use the pip command. If you type the code below it will install the module. That will install a Python module automatically.

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 import a Python module into pip?

Ensure you can run pip from the command lineRun python get-pip.py . 2 This will install or upgrade pip. Additionally, it will install setuptools and wheel if they're not installed already. Be cautious if you're using a Python install that's managed by your operating system or another package manager.

Where should Python modules be installed?

When a package is installed globally, it's made available to all users that log into the system. Typically, that means Python and all packages will get installed to a directory under /usr/local/bin/ for a Unix-based system, or \Program Files\ for Windows.


2 Answers

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]) 
like image 135
Aaron de Windt Avatar answered Oct 27 '22 08:10

Aaron de Windt


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') 
like image 31
Rikard Anglerud Avatar answered Oct 27 '22 07:10

Rikard Anglerud