如何从需要它的脚本内部安装缺少的 python 包?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17271444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to install a missing python package from inside the script that needs it?
提问by sorin
Assuming that you already have pip or easy_install installed on your python distribution, I would like to know how can I installed a required package in the user directory from within the script itself.
假设您已经在 python 发行版上安装了 pip 或 easy_install,我想知道如何从脚本本身在用户目录中安装所需的包。
From what I know pip is also a python module so the solution should look like:
据我所知 pip 也是一个 python 模块,所以解决方案应该是这样的:
try:
import zumba
except ImportError:
import pip
# ... do "pip install --user zumba" or throw exception <-- how?
import zumba
What I am missing is doing "pip install --user zumba" from inside python, I don't want to do it using os.system()as this may create other problems.
我缺少的是从 python 内部执行“pip install --user zumba”,我不想使用它,os.system()因为这可能会产生其他问题。
I assume it is possible...
我认为这是可能的......
采纳答案by sorin
Updated for newer pip version (>= 10.0):
更新了较新的 pip 版本 (>= 10.0):
try:
import zumba
except ImportError:
from pip._internal import main as pip
pip(['install', '--user', 'zumba'])
import zumba
Thanks to @Joop I was able to come-up with the proper answer.
感谢@Joop,我能够想出正确的答案。
try:
import zumba
except ImportError:
import pip
pip.main(['install', '--user', 'zumba'])
import zumba
One important remark is that this will work without requiring root access as it will install the module in user directory.
一个重要的说明是,这不需要 root 访问权限就可以工作,因为它将在用户目录中安装模块。
Not sure if it will work for binary modules or ones that would require compilation, but it clearly works well for pure-python modules.
不确定它是否适用于二进制模块或需要编译的模块,但它显然适用于纯 python 模块。
Now you can write self contained scripts and not worry about dependencies.
现在您可以编写自包含的脚本而不必担心依赖项。
回答by Casey
I wanted to note that the current accepted answer could result in a possible app name collision. Importing from the app namespace doesn't give you the full picture of what's installed on the system.
我想指出,当前接受的答案可能会导致应用程序名称冲突。从应用程序命名空间导入并不能让您全面了解系统上安装的内容。
A better way would be:
更好的方法是:
import pip
packages = [package.project_name for package in pip.get_installed_distributions()]
if 'package' not in packages:
pip.main(['install', 'package'])
回答by Phoenix
As of pip version >= 10.0.0, the above solutions will not work because of internal package restructuring. The new way to use pip inside a script is now as follows:
自 pip 版本 >= 10.0.0 起,由于内部包重组,上述解决方案将不起作用。现在在脚本中使用 pip 的新方法如下:
try: import abc
except ImportError:
from pip._internal import main as pip
pip(['install', '--user', 'abc'])
import abc

