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.
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.
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.
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.
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.
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])
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With