-3

I'm trying to install automatically each library in python if it isn't installed.

#!/usr/bin/python
# -*- coding: utf-8 -*-

from pip._internal import main
pkgs = ['Bio==0.1.0','argparse==1.4.0']
for package in pkgs:
    try:
        import package
    except ImportError:
        main(['install', package])

But, this error occurs:

Collecting Bio==0.1.0
Using cached https://files.pythonhosted.org/packages/14/c2/43663d53b93ef7b4d42cd3550631552887f36db02c0150d803c69ba636a6/bio-0.1.0-py2.py3-none-any.whl 
Installing collected packages: Bio 
Successfully installed Bio-0.1.0 
Collecting argparse==1.4.0   
Using cached https://files.pythonhosted.org/packages/f2/94/3af39d34be01a24a6e65433d19e107099374224905f1e0cc6bbe1fd22a2f/argparse-1.4.0-py2.py3-none-any.whl 
ERROR: Could not install packages due to an EnvironmentError: [Errno2] No such file or directory: '/tmp/pip-req-tracker-6sqtap8q/139713c65f8ac559a034717470dc5a6e30a6db86bdc3d69fe2bc0e63'

I notice that this occur always after the first library installation, e.g.: If I change ['Bio','argparse'] for ['argparse','Bio'], then argparse will be installed, but Bio will not.

3
  • 1
    Does this answer your question? Installing python module within code Commented Dec 16, 2019 at 11:09
  • Also consider the top two answers to stackoverflow.com/questions/6120902/… Commented Dec 16, 2019 at 11:10
  • 4
    from pip._internal import main The underscore in _internal means, "don't use this". In fact, pip's main() function was deliberately moved into a pip._internal module in order to discourage people from using it this way, as it is not at all safe to do so. Automatically installing packages, while it may seem convenient, is ultimately user-hostile as it modifies their system in potentially unpredictable ways. Instead, please just raise an except noting what dependencies are missing. Commented Dec 16, 2019 at 11:11

1 Answer 1

2

Do not do this.

Instead:

  • either actually package your Python project properly with accurate dependencies (look up setuptools, poetry, flit, or any other similar project);

  • or instruct your users to install your project's dependencies themselves, you can facilitate this by providing a pip-compatible requirements.txt file.

Additional note here is how to "Using pip from your program".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.