如何检查模块是否安装在 Python 中,如果没有,则将其安装在代码中? [英] How to check if a module is installed in Python and, if not, install it within the code?

查看:43
本文介绍了如何检查模块是否安装在 Python 中,如果没有,则将其安装在代码中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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.

推荐答案

EDIT - 2020/02/03

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

The pip module 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 subprocess and pkg_resources, and not pip.

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

To hide the output, you can redirect the subprocess output to 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)

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

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.

这篇关于如何检查模块是否安装在 Python 中,如果没有,则将其安装在代码中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆