pip.main install fails with 'module' object has no attribute 'main'

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

2 answers

  • answered 2018-04-17 10:19 kaxil

    I had the same issue and just running the below command solved it for me:

    easy_install pip
    

  • answered 2018-04-17 16:16 e.s.

    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 install requests 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 or pip install) is a different matter. There are well-established ways to install other packages using requirements.txt and setup.py. It is also expected that installing a package will install its dependencies. You can read more in the python.org packaging tutorials

    If your script has dependencies but people don't need to install it, you should tell them in the README.rst and/or requirements.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.