use "pip install/uninstall" inside a python script

pip.main() no longer works in pip version 10 and above. You need to use:

from pip._internal import main as pipmain

pipmain(['install', 'package-name'])

For backwards compatibility you can use:

try:
    from pip import main as pipmain
except ImportError:
    from pip._internal import main as pipmain

It's not a good idea to install packages inside the python script because it requires root rights. You should ship additional modules alongside with the script you created or check if the module is installed:

try:
   import ModuleName
except ImportError:
   print 'Error, Module ModuleName is required'

If you insist in installing the package using pip inside your script you'll have to look into call from the subprocess module ("os.system()" is deprecated).

There is no pip module but you could easily create one using the method above.


I think those answers are outdated. In fact you can do:

import pip
failed = pip.main(["install", nameOfPackage])

and insert any additional args in the list that you pass to main(). It returns 0 (failed) or 1 (success)

Jon

Tags:

Python

Pip