pip.main install fails with 'module' objec

2019-05-18 04:50发布

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

4条回答
Luminary・发光体
2楼-- · 2019-05-18 05:13

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.

查看更多
叛逆
3楼-- · 2019-05-18 05:20

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

try:
    import requests
except:
    import sys
    import subprocess
    subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'requests==2.0.1', 'PyYAML==3.11'])
    import requests
查看更多
疯言疯语
4楼-- · 2019-05-18 05:29

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.

查看更多
虎瘦雄心在
5楼-- · 2019-05-18 05:30

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

easy_install pip
查看更多
登录 后发表回答