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

编程入门 行业动态 更新时间:2024-10-10 15:19: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 模块已经更新了很多.我已经使用正确的方法更新了代码片段以安装缺少的依赖项,即使用 subprocess 和 pkg_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 中,如果没有,则将其安装在代码中?

本文发布于:2023-06-11 03:30:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/625702.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:安装在   如果没有   则将   模块   代码

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!