I am trying to install few of the python packages from within a python script and I am using pip.main(install)
for that. Below is code snippet
try:
import requests
except:
import pip
pip.main(['install', '-q', 'requests==2.0.1','PyYAML==3.11'])
import requests
I have tried using importing main from pip._internal and using pipmain instead of pip.main() but it did not help.
I am on pip version 9.0.1
and python 2.7
The pip.main function was moved, not removed by pip devs. The highest voted solution here is not good. Going from python -> shell -> python is not a good practice when you can just run the python code direct. Try
from pip._internal import main
then you can use that main function to execute your pip calls like before.pip Developers do not recommend calling pip from within the program. And the pip.main() method has been removed from pip v10. As an alternative method it is recommended to execute pip in subprocess.
https://pip.pypa.io/en/stable/user_guide/?highlight=_internal#using-pip-from-your-program
The short answer is don't do this. Use
setup.py
or a straight import statement.Here is why this doesn't work with pip and how to get around it if necessary.
pip
affects the whole environment. Depending on who is running this and why, they may or may not want to installrequests
in the environment they're running your script in. It could be a nasty surprise that running your script affects their python environment.Installing it as a package (using
python setup.py
orpip install
) is a different matter. There are well-established ways to install other packages usingrequirements.txt
andsetup.py
. It is also expected that installing a package will install its dependencies. You can read more in the python.org packaging tutorialsIf your script has dependencies but people don't need to install it, you should tell them in the
README.rst
and/orrequirements.txt
. or simply include the import statement, and when they get the error, they'll know what to do. Let them control what environment installs which packages.I had the same issue and just running the below command solved it for me: