-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.

Edward Minnix
  • 2,889
  • 1
  • 13
  • 26
heuristic
  • 41
  • 6
  • 1
    Does this answer your question? [Installing python module within code](https://stackoverflow.com/questions/12332975/installing-python-module-within-code) – mkrieger1 Dec 16 '19 at 11:09
  • Also consider the top two answers to https://stackoverflow.com/questions/6120902/how-do-i-automatically-install-missing-python-modules – mkrieger1 Dec 16 '19 at 11:10
  • 3
    `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. – Iguananaut Dec 16 '19 at 11:11

1 Answers1

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".

sinoroc
  • 18,409
  • 2
  • 39
  • 70