如何检查模块是否安装在 Python 中,如果没有,则将其安装在代码中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44210656/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:50:03  来源:igfitidea点击:

How to check if a module is installed in Python and, if not, install it within the code?

pythonpython-3.xmodulepython-module

提问by Gameskiller01

I would like to install the modules 'mutagen' and 'gTTS' for my code, but I want to have it so it will install the modules on every computer that doesn't have them, but it won't try to install them if they're already installed. I currently have:

我想为我的代码安装模块 'mutagen' 和 'gTTS',但我想要它,所以它会在没有它们的每台计算机上安装模块,但它不会尝试安装它们,如果他们已经安装了。我目前有:

def install(package):
    pip.main(['install', package])

install('mutagen')

install('gTTS')

from gtts import gTTS
from mutagen.mp3 import MP3

However, if you already have the modules, this will just add unnecessary clutter to the start of the program whenever you open it.

但是,如果您已经拥有这些模块,那么每当您打开它时,这只会在程序的开头添加不必要的混乱。

回答by theGirrafish

EDIT - 2020/02/03

编辑 - 2020/02/03

The pipmodule has updated quite a lot since the time I posted this answer. I've updated the snippet with the proper way to install a missing dependency, which is to use subprocessand pkg_resources, and not pip.

pip自从我发布这个答案以来,该模块已经更新了很多。我已经用正确的方法更新了代码片段来安装缺少的依赖项,即使用subprocessand pkg_resources,而不是pip

To hide the output, you can redirect the subprocess output to devnull:

要隐藏输出,您可以将子进程输出重定向到 devnull:

import sys
import subprocess
import pkg_resources

required = {'mutagen', 'gTTS'}
installed = {pkg.key for pkg in pkg_resources.working_set}
missing = required - installed

if missing:
    python = sys.executable
    subprocess.check_call([python, '-m', 'pip', 'install', *missing], stdout=subprocess.DEVNULL)

Like @zwer mentioned, the above works, although it is not seen as a proper way of packaging your project. To look at this in better depth, read the the page How to package a Python App.

就像@zwer 提到的那样,上面的方法是有效的,尽管它不被视为打包项目的正确方式。要更深入地了解这一点,请阅读如何打包 Python 应用程序页面

回答by Hyman

pip list | grep <module_name_you_want_to_check>

Above is the answer, where:

以上是答案,其中:

pip list

list all modules, and

列出所有模块,以及

grep <module_name_you_want_to_check>

find the keyword from the list. Works for me.

从列表中找到关键字。为我工作。

回答by Joseph Long

Another solution it to put an import statement for whatever you're trying to import into a try/except block, so if it works it's installed, but if not it'll throw the exception and you can run the command to install it.

另一个解决方案是将您尝试导入的任何内容的导入语句放入 try/except 块中,因此如果它可以正常工作,则它已安装,但如果没有,它将抛出异常,您可以运行命令来安装它。

回答by D. Peter

You can use the command line :

您可以使用命令行:

python -m MyModule

it will say if the module exists

它会说模块是否存在

Else you can simply use the best practice :

否则,您可以简单地使用最佳实践:

pip freeze > requirements.txt

pip冻结>需求.txt

That will put the modules you've on you python installation in a file

这会将您安装的模块放在一个文件中

and :

和 :

pip install -r requirements.txt

pip install -r requirements.txt

to load them

加载它们

It will automatically you purposes

它会自动你的目的

Have fun

玩得开心

回答by dcoles

You can check if a package is installed using pkg_resources.get_distribution:

您可以使用以下命令检查是否安装了软件包pkg_resources.get_distribution

import pkg_resources

for package in ['mutagen', 'gTTS']:
    try:
        dist = pkg_resources.get_distribution(package)
        print('{} ({}) is installed'.format(dist.key, dist.version))
    except pkg_resources.DistributionNotFound:
        print('{} is NOT installed'.format(package))

Note:You should not be directly importing the pipmodule as it is an unsupported use-caseof the pipcommand.

注意:您不应直接导入pip模块,因为它是pip命令的不受支持的用例

The recommended way of using pipfrom your programis to execute it using subprocess:

从程序中使用pip推荐方法是使用以下命令执行它subprocess

subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'my_package'])