[英]try import if not, install in python
I'm trying to install automatically each library in python if it isn't installed.如果未安装,我正在尝试在 python 中自动安装每个库。
#!/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, eg: If I change ['Bio','argparse']
for ['argparse','Bio']
, then argparse
will be installed, but Bio
will not.我注意到这总是在第一个库安装之后发生,例如:如果我将
['Bio','argparse']
更改为['argparse','Bio']
,那么argparse
将被安装,但Bio
不会。
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);无论是实际精确的依赖关系(看看正确打包Python项目setuptools的,诗歌,迁徙,或者其他任何类似的项目);
or instruct your users to install your project's dependencies themselves, you can facilitate this by providing a pip -compatible requirements.txt
file .或者指示您的用户自己安装项目的依赖项,您可以通过提供pip兼容的
requirements.txt
文件来促进此操作。
Additional note here is how to "Using pip from your program" .这里的附加说明是如何“使用程序中的 pip” 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.